package org.ezplatform.office.meeting.info.web.rest;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.ezplatform.cloud.api.component.attachment.AttachmentUtilsService;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.controller.BaseController;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.component.popuser.service.CmpPopUserOrgName;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.mobile.util.common.service.CommonService;
import org.ezplatform.mobile.util.paramdata.service.MobileParamdataService;
import org.ezplatform.office.meeting.common.util.CycleMeetingThread;
import org.ezplatform.office.meeting.common.util.MeetingSendMsgUtils;
import org.ezplatform.office.meeting.common.util.MeetingUtils;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.info.entity.MeetingScope;
import org.ezplatform.office.meeting.info.entity.QSMeetingInfo;
import org.ezplatform.office.meeting.info.entity.SignedAddress;
import org.ezplatform.office.meeting.info.entity.SignedInfo;
import org.ezplatform.office.meeting.info.entity.Urlconvert;
import org.ezplatform.office.meeting.info.service.ApplyRecordDingService;
import org.ezplatform.office.meeting.info.service.ApplyRecordService;
import org.ezplatform.office.meeting.info.service.MeetingScopeService;
import org.ezplatform.office.meeting.info.service.QSMeetingService;
import org.ezplatform.office.meeting.info.service.SignedAddressService;
import org.ezplatform.office.meeting.info.service.SignedInfoService;
import org.ezplatform.office.meeting.info.service.UrlconvertService;
import org.ezplatform.office.meeting.memo.entity.MemoInfo;
import org.ezplatform.office.meeting.memo.entity.MemoUserInfo;
import org.ezplatform.office.meeting.memo.service.MemoInfoService;
import org.ezplatform.office.meeting.memo.service.MemoUserInfoService;
import org.ezplatform.office.meeting.notice.entity.NoticeInfo;
import org.ezplatform.office.meeting.notice.entity.NoticeTurnover;
import org.ezplatform.office.meeting.notice.service.NoticeInfoService;
import org.ezplatform.office.meeting.notice.service.NoticeTurnoverService;
import org.ezplatform.office.meeting.search.service.SearchService;
import org.ezplatform.office.meeting.setting.base.entity.BaseSet;
import org.ezplatform.office.meeting.setting.base.service.BaseSetService;
import org.ezplatform.office.meeting.setting.boardroom.entity.BoardroomSet;
import org.ezplatform.office.meeting.setting.boardroom.service.BoardroomSetService;
import org.ezplatform.office.meeting.setting.category.entity.BoardroomCategorySet;
import org.ezplatform.office.meeting.setting.category.service.BoardroomCategorySetService;
import org.ezplatform.office.meeting.setting.serve.service.ServeSetService;
import org.ezplatform.office.meeting.task.entity.MeetingTaskInfo;
import org.ezplatform.office.meeting.task.service.MeetingTaskInfoService;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.GlobalConstant;
import org.ezplatform.util.JsonUtils;
import org.ezplatform.util.ResponseResult;
import org.ezplatform.util.RestClient;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.swetake.util.Qrcode;

import io.swagger.annotations.ApiOperation;

/**
 * 
 *会议管理--会议通知
 *
 */
@RestController
@RequestMapping("/api/m/office/meeting")
public class ApplyRecordApiMobileController extends BaseController {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(ApplyRecordApiMobileController.class);
	
	@Autowired
	private BaseSetService service;
	
    @Autowired
    private UserApiService userApiService;
    
    @Autowired
	private ApplyRecordService applyRecordService;
    
    @Autowired
	private NoticeTurnoverService noticeTurnoverService;
    
    @Autowired
    private NoticeInfoService noticeInfoService;
    
    @Autowired
    private ApplyRecordDingService applyRecordDingService;

    @Autowired
    private MemoInfoService memoInfoService;
    
    @Autowired
    private MemoUserInfoService memoUserInfoService;
    
    @Autowired
    private MeetingScopeService meetingScopeService;
    
    @Autowired
    private BoardroomSetService boardroomSetService;
	
	@Autowired
	private MeetingSendMsgUtils meetingSendMsgUtils;
	
	@Autowired
    private BoardroomCategorySetService boardroomCategorySetService;
    
	@Autowired
	private ServeSetService serveSetService;
	
	@Autowired
    private SearchService searchService;
	
	@Autowired
	private SignedAddressService signedAddressService;
	
	@Autowired
	private SignedInfoService signedInfoService;
	
	@Autowired
    private PopUserScopeUtilService popUserScopeUtilService;
	
	@Autowired
	private MeetingTaskInfoService meetingTaskInfoService;
	
	@Autowired
	private MobileParamdataService mobileParamdataService;
	
	@Autowired
	private UrlconvertService urlconvertService;
	
	@Autowired
	private AttachmentUtilsService attachmentUtilsService;

    @Autowired
	private LogService logService;
    
    @Autowired
	private MeetingUtils meetingUtils;
    
    @Autowired
	private QSMeetingService qsMeetingService;
    
    @Autowired
	private CommonService commonService;
    
	@Autowired
	private CmpPopUserOrgName cmpPopUserOrgName;
    
    /**
     * 会议通知
     */
    @ApiOperation(value="会议通知", notes="查询我参加会议的会议通知list列表数据")
    @RequestMapping(value="/attendNoticeInfoSetList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getAttendNoticeInfoSetList(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //用户ID
            String userId = user.getUserId();
            //用户单位
            String corpId = user.getCorpId();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition");
            String nowDateTime = DateUtils.formatDate(DateUtils.now(),"yyyy-MM-dd HH:mm");
            //查询会议通知列表数据
            List<Map> list = this.noticeInfoService.getNoticeInfoSetList(currentPage, pageSize,userId,corpId,"0",condition,1,nowDateTime);
            //查询会议申请列表数count
            int approvalCount = this.noticeInfoService.getNoticeInfoSetListCount(userId,corpId,"1","",0,nowDateTime);
            //查询会议纪要未读列表数count
            int memoCount = this.memoInfoService.getMemoInfoListCount(userId, corpId);
            resultMap.put("data", list);
            resultMap.put("approvalCount", approvalCount);
            resultMap.put("memoCount", memoCount);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    /**
     * 会议通知
     */
    @ApiOperation(value="会议通知", notes="查询我审批会议的会议通知list列表数据")
    @RequestMapping(value="/approvalNoticeInfoSetList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getApprovalNoticeInfoSetList(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //用户ID
            String userId = user.getUserId();
            //用户单位
            String corpId = user.getCorpId();
          //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition");
            String nowDateTime = DateUtils.formatDate(DateUtils.now(),"yyyy-MM-dd HH:mm:ss");
            List<Map> list = this.noticeInfoService.getNoticeInfoSetList(currentPage, pageSize,userId,corpId,"0",condition,0,nowDateTime);
            //查询会议申请列表数count
            //int approvalCount = this.noticeInfoDingService.getNoticeInfoSetListCount(userId,corpId,"1","",0,nowDateTime);
            //查询会议纪要未读列表数count
            //int memoCount = this.memoInfoService.getMemoInfoListCount(userId, corpId);
            resultMap.put("data", list);
            //map.put("approvalCount", approvalCount);
            //map.put("memoCount", memoCount);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    /**
     * 会议通知详细页面数据
     * @param request
     * @return
     */
    @ApiOperation(value="会议通知", notes="查看会议通知详细信息")
    @RequestMapping(value="/attendNoticeInfo", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getAttendNoticeInfo(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            String corpId = user.getCorpId();
            String token = user.getJwtToken();
            String userId = user.getUserId();
            String applyRecordId = request.getParameter("id");
            String type = StringUtils.null2String(request.getParameter("type"));
            if(type == ""){
            	type = "1";
            }
            String nStatus = "";
            ApplyRecord applyRecord = this.applyRecordDingService.findOne(applyRecordId);
            if(applyRecord == null) {
            	map.put("isDeleted", true);
            	return ResponseResult.buildSuccessResult(map);
            }
        	map.put("isDeleted", false);
        	List<Map> serveSetCheckList = new ArrayList<Map>();//会议申请选中的会议服务
        	BoardroomSet boardroomSet = null;
			String boardroomId = applyRecord.getBoardroomId();
			if(StringUtils.isNotEmpty(boardroomId)) {
				boardroomSet = this.boardroomSetService.findOne(boardroomId);
			}
			serveSetCheckList = this.serveSetService.getServeSetCheckList(applyRecord.getMeetingServe());
			//发起人
			String createdBy = applyRecord.getCreatedBy();
			Map<String, Object> userMap = this.userApiService.getUser(createdBy, corpId, "", token);
			map.put("createdName", userMap != null ? userMap.get("userName") : "");
			map.put("applyRecord", applyRecord);
        	map.put("serveSetCheckList", serveSetCheckList);
        	map.put("boardroomSet", boardroomSet);
        	boolean needPostionSigned = false, needQrcodeSigned = false;
        	String signedDateTime = "";
        	if(applyRecord.getIsSigned() == 1) {
        		List<String> meetingUserIdList = this.applyRecordService.getApplyRecordUserList(applyRecord, token);
            	if(meetingUserIdList.contains(userId)) {//是参会人员
            		if("0".equals(applyRecord.getSignedType())) needQrcodeSigned = true;
            		else if("1".equals(applyRecord.getSignedType())) needPostionSigned = true;
            		else if("2".equals(applyRecord.getSignedType())) {
            			needQrcodeSigned = true;
            			needPostionSigned = true;
            		}
            	}
				String startDateTime = applyRecord.getStartTime();
				String signedTime = applyRecord.getSignedTime();
				String signedTimeStr = this.getDateTimeStr(startDateTime.substring(11, 16), Integer.valueOf(signedTime), 1);
				signedDateTime = startDateTime.substring(0,10)+" "+signedTimeStr+":00";
        	}
        	map.put("needPostionSigned", needPostionSigned);
        	map.put("needQrcodeSigned", needQrcodeSigned);
        	map.put("signedDateTime", signedDateTime);
            //会议通知数据处理
            NoticeInfo noticeInfo = new NoticeInfo();
            noticeInfo = this.noticeInfoService.findByApplyrecordId(applyRecordId, userId, type);
            List<NoticeTurnover> ntList = this.noticeTurnoverService.findNoticeTurnoverList(applyRecordId, userId, corpId);
//            map = this.applyRecordDingService.getApproveApplyRecordContent(applyRecordId,corpId,token);
            if(ntList != null && ntList.size() > 0) map.put("isTurnover", true);
            else map.put("isTurnover", false);
            int isSigned = applyRecord.getIsSigned();
            if(noticeInfo != null){
            	int status = noticeInfo.getStatus();
                if(status==0){
                    nStatus = "0";
                }else{
                    nStatus = "2";
                    if(isSigned==1){
                        nStatus = "1";
                    }
                }
            }
            map.put("noticeInfo", noticeInfo);
            map.put("nStatus",nStatus);
        }catch(Exception e){
        	e.printStackTrace();
        	map.put("success", false);
        	map.put("content", "");
        }
        return ResponseResult.buildSuccessResult(map);
    }
    
    /**
     * 转本部门
     */
    @ApiOperation(value = "转本部门", notes = "转本部门")
    @RequestMapping(value = "/saveTurnoverInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult saveTurnoverInfo(HttpServletRequest request) {
        try {
        	WebUser user = WebUtils.getCurrentUser();
            String corpId = user.getCorpId();
            String token = user.getJwtToken();
            String userId = user.getUserId();
            String userName = user.getCnName();
            String noticeInfoId = StringUtils.null2String(request.getParameter("id"));
            String applyRecordId = StringUtils.null2String(request.getParameter("meetingId"));
            String jsonStrReceiveUser = StringUtils.null2String(request.getParameter("jsonStrReceiveUser"));
    		String receiveUserId = "";
    		String receiveUserName = "";
    		String turnoverUserId = userId;
    		NoticeTurnover entity = new NoticeTurnover();
    		entity.setApplyRecordId(applyRecordId);
    		entity.setNoticeInfoId(noticeInfoId);
    		if(!"".equals(jsonStrReceiveUser)) {
    			Map<String, String> map = getUserId(jsonStrReceiveUser);
    			receiveUserId = map.get("id");
    			receiveUserName = map.get("name");
    			if(turnoverUserId.equals(receiveUserId)) {
    				return ResponseResult.buildFailureResult("接收人不能选自己");
    			}
    			if(noticeTurnoverService.findByApplyrecordId(entity.getApplyRecordId(), receiveUserId, corpId) != null) {
    				return ResponseResult.buildFailureResult("该用户已转交他人代替参会，请重新选择");
    			}
    			entity.setReceiveUserId(receiveUserId);
    			entity.setReceiveUserName(map.get("name"));
    		}
    		entity.setTurnoverUserId(turnoverUserId);
    		entity.setTurnoverUserName(userName);
    		ApplyRecord ar = applyRecordService.findOne(applyRecordId);
    		//主持人或纪要员或参与人替换
    		noticeTurnoverService.changeUser(ar, token, turnoverUserId, receiveUserId, receiveUserName);
    		//通知状态改为4
    		NoticeInfo ni = noticeInfoService.findOne(entity.getNoticeInfoId());
    		ni.setStatus(4);
    		ni.setReason(null);
    		noticeInfoService.save(ni);
    		//查询所有参会人
    		List<String> aruList = applyRecordService.getApplyRecordUserList(ar, token);
    		if(aruList.contains(receiveUserId)) {
    			//转交人是已参会人员，就不用新建通知数据
    			NoticeInfo noticeInfo = this.noticeInfoService.findByApplyrecordId(entity.getApplyRecordId(), receiveUserId, "1");
    			if(noticeInfo != null && StringUtils.isNotEmpty(noticeInfo.getId())) {
    				noticeInfo.setStatus(5);
    				noticeInfoService.save(ni);
    			}
    		}else{
    			//转交人可查看通知，新建转交人通知数据
    			NoticeInfo receiveNi = new NoticeInfo();
    			receiveNi.setStatus(5);
    			receiveNi.setApplyRecordId(ni.getApplyRecordId());
    			receiveNi.setType(ni.getType());
    			receiveNi.setNoticeUserId(receiveUserId);
    			noticeInfoService.save(receiveNi);
    		}
    		this.sendMessageToTurnoverUser(request, ar, userId, receiveUserId, corpId, token);
    		noticeTurnoverService.save(entity);
        } catch (Exception e) {
        	return ResponseResult.buildFailureResult("转本部门失败");
        }
        return ResponseResult.buildSuccessResult("转本部门成功");
    }
    
    /**
     * 转本部门数据提交前校验
     */
    @ApiOperation(value = "转本部门数据提交前校验", notes = "转本部门数据提交前校验")
    @RequestMapping(value = "/checkTurnoverDate", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult checkTurnoverDate(HttpServletRequest request) {
        try {
        	WebUser user = WebUtils.getCurrentUser();
            String corpId = user.getCorpId();
            String turnoverUserId = user.getUserId();
            String applyRecordId = StringUtils.null2String(request.getParameter("meetingId"));
    		ApplyRecord ar = applyRecordService.findOne(applyRecordId);
    		if(ar == null) {
    			return ResponseResult.buildFailureResult("当前数据已删除");
    		}
    		if(noticeTurnoverService.findByApplyrecordId(applyRecordId, turnoverUserId, corpId) != null) {
    			return ResponseResult.buildFailureResult("该会议您已转交他人");
    		}
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.buildSuccessResult("");
    }
    
    /**
     * 修改修改会议通知状态
     */
    @ApiOperation(value = "修改会议通知状态", notes = "确认参会、请假")
    @RequestMapping(value = "/editNoticeInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult editNoticeInfo(HttpServletRequest request) {
        try {
            String id =  request.getParameter("id");
            String status =  request.getParameter("status");
            String reason =  request.getParameter("reason");
            
            if("1".equals(status)){
                this.noticeInfoService.editNoticeInfo(id,2,reason);
            }else if("2".equals(status)){
                this.noticeInfoService.editNoticeInfo(id,3,null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.buildFailureResult("保存会议通知状态失败");
        }
        return ResponseResult.buildSuccessResult("保存会议通知状态成功");
    }
    
    @ApiOperation(value = "转发", notes = "转发")
    @RequestMapping(value = "/turnoverSave", method = RequestMethod.POST)
    public ResponseResult turnoverSave(HttpServletRequest request) {
        try {
        	String id = ValidateUtils.filter(request.getParameter("id"));
        	NoticeInfo entity = this.noticeInfoService.findOne(id);
        	if(entity == null) return ResponseResult.buildFailureResult("该会议已取消或变更");
			WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
			String token = user.getJwtToken();
			String turnoverUserId = user.getUserId();
			ApplyRecord ar = applyRecordService.findOne(entity.getApplyRecordId());
			if(ar == null) return ResponseResult.buildFailureResult("当前数据已删除");
			//查询所有参会人
			List<String> aruList = applyRecordService.getApplyRecordUserList(ar, user.getJwtToken());
			//邀请
			String jsonStrInviteUser = StringUtils.null2String(request.getParameter("jsonStrInviteUser"));
			if(StringUtils.isNotBlank(jsonStrInviteUser)){
				//已转交出去不参会的人
				List<String> turnoverUseIds = noticeInfoService.getTurnoverUseIds(ar.getId(), corpId);
				//被邀请参会的人
				List<String> inviteUserIds = noticeInfoService.getInviteUserIds(jsonStrInviteUser, aruList, turnoverUseIds);
				noticeInfoService.addNoticeInfo(inviteUserIds, ar.getId(), turnoverUserId, corpId);
				applyRecordService.addAttendUser(ar, inviteUserIds, corpId, token);
				noticeInfoService.sendMessageToTurnoverUser(request, ar, user.getUserId(), inviteUserIds, corpId, token);
			}
			//代参会
			String isAttendMeeting = StringUtils.null2String(request.getParameter("isAttendMeeting"));
			if("1".equals(isAttendMeeting)) {
				String jsonStrReceiveUser = StringUtils.null2String(request.getParameter("jsonStrReceiveUser"));
				String receiveUserId = "";
				if(StringUtils.isNotBlank(jsonStrReceiveUser)) {
					Map<String, String> map = noticeInfoService.getUserIdAndName(jsonStrReceiveUser);
					receiveUserId = map.get("id");
					if(turnoverUserId.equals(receiveUserId)) {
						return ResponseResult.buildFailureResult("代参会人不能选自己");
					}
					if(StringUtils.isNotBlank(entity.getReceiveUserId())) {
						return ResponseResult.buildFailureResult("该会议您已转交他人");
					}
					if(noticeInfoService.findByTurnoverUserId(entity.getApplyRecordId(), receiveUserId) != null) {
						return ResponseResult.buildFailureResult("该用户已转交他人代替参会，请重新选择");
					}
					entity.setReceiveUserId(receiveUserId);
				}
				//通知状态改为6
				entity.setStatus(6);
				entity.setReason(null);
				//转交人可查看通知，新建转交人通知数据
				NoticeInfo receiveNi = new NoticeInfo();
				receiveNi.setStatus(7);
				receiveNi.setType(2);
				receiveNi.setApplyRecordId(entity.getApplyRecordId());
				receiveNi.setNoticeUserId(receiveUserId);
				receiveNi.setTurnoverUserId(turnoverUserId);
				noticeInfoService.save(receiveNi);
				List<String> newUserIdList = new ArrayList<String>();
				newUserIdList.add(receiveUserId);
				if(ar.getIsSigned() == 1) this.signedInfoService.addSignedInfo(newUserIdList, ar.getId(), corpId);
				noticeInfoService.sendMessageToTurnoverUser(request, ar, user.getUserId(), newUserIdList, corpId, token);
				noticeInfoService.save(entity);
			}
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.buildFailureResult("邀请失败");
        }
        return ResponseResult.buildSuccessResult("邀请成功");
    }
    
    @ApiOperation(value = "修改会议通知状态", notes = "修改会议通知状态")
    @RequestMapping(value = "/editNoticeInfoStatus", method = RequestMethod.POST)
    public ResponseResult editNoticeInfoStatus(HttpServletRequest request) {
        try {
        	WebUser user = WebUtils.getCurrentUser();
    		String userId = user.getUserId();
    	    String token = user.getJwtToken();
			String id = ValidateUtils.filter(request.getParameter("id"));
			NoticeInfo entity = this.noticeInfoService.findOne(id);
			String applyRecordId = entity.getApplyRecordId();
			if(applyRecordId == null) return ResponseResult.buildFailureResult("当前数据已删除");
			String nStatus = ValidateUtils.filter(request.getParameter("status"));
			String attendWay = request.getParameter("attendWay");
			String reason = request.getParameter("reason");
			if("5".equals(nStatus)) {//代参会人确认参会
				//替换参会人
				ApplyRecord ar = applyRecordService.findOne(applyRecordId);
				String turnoverUserId = ValidateUtils.filter(request.getParameter("turnoverUserId"));
				noticeInfoService.changeUser(ar, token, turnoverUserId, userId, user.getCnName());
				List<NoticeInfo> saveList = new ArrayList<NoticeInfo>();
				NoticeInfo myNoticeInfo = noticeInfoService.findByApplyrecordId(applyRecordId, userId, "1");
				if(myNoticeInfo == null) {//本人还未参会过，新建参会通知
					NoticeInfo ni = new NoticeInfo();
					ni.setStatus(5);
					ni.setType(1);
					ni.setApplyRecordId(applyRecordId);
					ni.setNoticeUserId(userId);
					ni.setTurnoverUserId(turnoverUserId);
					saveList.add(ni);
				}
				NoticeInfo turnoverUserNoticeInfo = noticeInfoService.findByApplyrecordId(applyRecordId, turnoverUserId, "1");
				turnoverUserNoticeInfo.setStatus(4);//转交人通知状态改为4（代参会邀请得到确认）
				saveList.add(turnoverUserNoticeInfo);
				noticeInfoService.save(saveList);
				noticeInfoService.delete(entity);//删除代参会确认通知
			}else if("8".equals(nStatus)) {//代参会遭拒
				String turnoverUserId = ValidateUtils.filter(request.getParameter("turnoverUserId"));
				NoticeInfo turnoverUserNoticeInfo = noticeInfoService.findByApplyrecordId(applyRecordId, turnoverUserId, "1");
				turnoverUserNoticeInfo.setStatus(8);//转交人通知状态改为8（代参会邀请被拒绝）
				turnoverUserNoticeInfo.setReason(reason);
				noticeInfoService.save(turnoverUserNoticeInfo);
				noticeInfoService.delete(entity);
			}else {
				entity.setReason(reason);
			    entity.setStatus(Integer.valueOf(nStatus));
			    if(StringUtils.isNotBlank(attendWay)) entity.setAttendWay(Integer.valueOf(attendWay));
			    noticeInfoService.save(entity);
			}
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.buildFailureResult("保存失败");
        }
        return ResponseResult.buildSuccessResult("保存成功");
    }
    
    public String getRequestPayload(HttpServletRequest req) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = req.getReader();
            Throwable localThrowable3 = null;
            try {
                char[] buff = new char[1024];
                int len;
                while ((len = reader.read(buff)) != -1)
                    sb.append(buff, 0, len);
            } catch (Throwable localThrowable1) {
                localThrowable3 = localThrowable1;
                throw localThrowable1;
            } finally {
                if (reader != null)
                    if (localThrowable3 != null)
                        try {
                            reader.close();
                        } catch (Throwable localThrowable2) {
                            localThrowable3.addSuppressed(localThrowable2);
                        }
                    else
                        reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sb.toString();
    }
    
    /**
     * 查询我发起的会议数据
     */
    @ApiOperation(value="会议查询", notes="查询我发起的会议list列表数据信息")
    @RequestMapping(value="/createApplyRecordList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getCreateApplyRecordList(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition");
            //用户ID
            String userId = user.getUserId();
            //用户单位
            String corpId = user.getCorpId();
            String token = user.getJwtToken();
            
            List<Map> list = this.searchService.getApplyRecordListOfMine(currentPage, pageSize,userId,corpId,condition,token);
            resultMap.put("data", list);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
            
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    /**
     * 查询我参与的会议数据
     */
    @ApiOperation(value="会议查询", notes="查询我参与的会议list列表数据信息")
    @RequestMapping(value="/attendApplyRecordList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getAttendApplyRecordList(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition"); 
            //用户ID
            String userId = user.getUserId();
            //用户单位
            String corpId = user.getCorpId();
            String token = user.getJwtToken();
            
            List<Map> list = this.searchService.getApplyRecordListOfMine(currentPage, pageSize, userId, corpId, condition, token);
            resultMap.put("data", list);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
           
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    /**
     * 查询与我有关的周期会议
     */
    @ApiOperation(value="周期会议查询", notes="查询与我有关的周期会议列表数据信息")
    @RequestMapping(value="/getCycleMeetingList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getCycleMeetingList(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition"); 
            String userId = user.getUserId();
            String corpId = user.getCorpId();
            String token  = user.getJwtToken();
            List<Map> list = this.searchService.getCycleMeetingListOfMine(currentPage, pageSize, userId, corpId, condition, token);
            resultMap.put("data", list);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
            
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    @ApiOperation(value="回执统计查询", notes="回执统计查询")
    @RequestMapping(value="/getReceiptStatistics", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getReceiptStatistics(HttpServletRequest request) {
    	LOGGER.debug("-----getReceiptStatistics----");
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition"); 
            String applyRecordId = request.getParameter("applyRecordId"); 
            String status = request.getParameter("status");
            String corpId = user.getCorpId();
            
            LOGGER.debug("--currentPage:"+currentPage);
            LOGGER.debug("--pageSize:"+pageSize);
            LOGGER.debug("--condition:"+condition);
            LOGGER.debug("--applyRecordId:"+applyRecordId);
            LOGGER.debug("--status:"+status);
            LOGGER.debug("--corpId:"+corpId);
            
            List<Map> list = this.noticeInfoService.getReceiptStatisticsDing(applyRecordId,currentPage, pageSize, status, corpId, condition);
            resultMap.put("data", list);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
            
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    /**
     * 根据周期会议id查询周期会议
     */
    @ApiOperation(value="周期会议查询", notes="根据周期会议id查询周期会议")
    @RequestMapping(value="/getCycleMeetingByCycleId", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getCycleMeetingByCycleId(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition"); 
            String cycleId = request.getParameter("id"); 
            String userId = user.getUserId();
            String corpId = user.getCorpId();
            String token  = user.getJwtToken();
            List<Map> list = this.searchService.getCycleMeetingByCycleId(currentPage, pageSize, userId, corpId, condition, cycleId, token);
            resultMap.put("data", list);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    @ApiOperation(value = "实体类是否存在", notes = "")
	@RequestMapping(value="/entityIsExist", method=RequestMethod.POST, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public ResponseResult entityIsExist(HttpServletRequest request) {
		String id = request.getParameter("id");
		ApplyRecord entity = this.applyRecordDingService.findOne(id);
		if(entity == null) return ResponseResult.buildSuccessResult("notExist");
		else return ResponseResult.buildSuccessResult("exist");
    }
    
    @ApiOperation(value = "实体类是否存在", notes = "")
	@RequestMapping(value="/cycleEntityIsExist", method=RequestMethod.POST, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public ResponseResult cycleEntityIsExist(HttpServletRequest request) {
    	String id = request.getParameter("id");
        String corpId = request.getParameter("corpId");
		List<ApplyRecord> list = this.applyRecordDingService.findListByProperty("cycleId", id, corpId);
		if(CollectionUtils.isEmpty(list)) return ResponseResult.buildSuccessResult("notExist");
		else return ResponseResult.buildSuccessResult("exist");
    }
    
    @ApiOperation(value = "实体类是否存在", notes = "")
	@RequestMapping(value="/taskIsExist", method=RequestMethod.POST, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public ResponseResult taskIsExist(HttpServletRequest request) {
		String id = request.getParameter("id");
		MeetingTaskInfo entity = this.meetingTaskInfoService.findOne(id);
		if(entity == null) return ResponseResult.buildSuccessResult("notExist");
		else return ResponseResult.buildSuccessResult("exist");
    }
    
    @ApiOperation(value = "实体类是否存在", notes = "")
	@RequestMapping(value="/memoIsExist", method=RequestMethod.POST, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public ResponseResult memoIsExist(HttpServletRequest request) {
		String id = request.getParameter("id");
		MemoInfo entity = this.memoInfoService.findOne(id);
		if(entity == null) return ResponseResult.buildSuccessResult("notExist");
		else return ResponseResult.buildSuccessResult("exist");
    }
    
    /**
	 * 会议申请详细页面数据
	 * 
	 * @param request
	 * @return
	 */
	@ApiOperation(value = "会议申请", notes = "新建、编辑查看会议申请详细信息")
	@RequestMapping(value="/applyRecordInfo", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public ResponseResult getApplyRecordInfo(HttpServletRequest request) {
		LOGGER.debug("-----getApplyRecordInfo----");
		Map<String, Object> map = new HashMap<String, Object>();
		WebUser user = WebUtils.getCurrentUser();
		try {
			String token = "";
			String corpId = "";
			String userId = "";
			if(user != null){
				corpId = user.getCorpId();
				userId = user.getUserId();
				token = user.getJwtToken();
			}
			LOGGER.debug("--token:"+token);
			String id = request.getParameter("id");
			String boardroomId = request.getParameter("boardroomId");
			String type = request.getParameter("type");
			LOGGER.debug("--id:"+id);
			String fileId = "";
			if(StringUtils.isNotEmpty(id)) {
				ApplyRecord applyRecord = this.applyRecordDingService.findOne(id);
				if(applyRecord == null) {
	            	map.put("isDeleted", true);
	            	return ResponseResult.buildSuccessResult(map);
	            }
				fileId = applyRecord.getFileId();
			}
			LOGGER.debug("--type:"+type);
			//查询会议content
			if("view".equals(type)){
				map = this.applyRecordDingService.getViewApplyRecordContent(request,id,userId,corpId,token);
			}else{
				map = this.applyRecordDingService.getApplyRecordContent(id,userId,corpId,token);
			}
			String messagePushSW = commonService.getMessagePush(corpId, token,"meeting");
			LOGGER.debug("--messagePushSW:"+messagePushSW);
			map.put("messagePushSW", messagePushSW);
			Object attIdJson = this.applyRecordDingService.transformAttachmentPlanform2Dd(StringUtils.null2String(fileId), token);
			map.put("attIdJson", attIdJson);
            map.put("fileIds", StringUtils.null2String(fileId));
			map.put("isDeleted", false);
            if(StringUtils.isNotEmpty(boardroomId)){
            	List serveSetList = this.serveSetService.getBoardRoomServeTreeDataList(corpId,boardroomId);
                map.put("serveSetList", serveSetList);
                BoardroomSet boardroom = this.boardroomSetService.findOne(boardroomId);
                if(boardroom != null) {
                	String limitDate = this.boardroomSetService.getLimitDate(boardroom.getBeforeDays());
                	map.put("limitDate", limitDate);
                }
                map.put("boardRoom", boardroom);
            }else {
            	String serveSetListStr=this.serveSetService.getServeTreeData(request,corpId);
            	serveSetListStr=serveSetListStr.replace("id", "value").replace("name","text");
            	map.put("serveSetList", JsonUtils.readListValue(serveSetListStr));
            }
            BaseSet baseSet = this.service.getBaseSetInfo(corpId);
            String signedType = baseSet.getSignedType();
            String meetingWay = baseSet.getMeetingWay();
            LOGGER.debug("--signedType:"+signedType);
            String signedTypeStr = "";
            if(signedType!=null) {
            	signedTypeStr += "[";
            	if(signedType.indexOf("|0|")!=-1){
            		signedTypeStr += "{ value: '0', text: '扫码' },";
			    }
			   if(signedType.indexOf("|1|")!=-1){
				   signedTypeStr += "{ value: '1', text: '定位' },";
			   }
			   if(signedType.indexOf("|2|")!=-1){
				   signedTypeStr += "{ value: '2', text: '扫码+定位' },";
			   }
			   if(signedType.indexOf("|3|")!=-1){
				   signedTypeStr += "{ value: '3', text: '现场签到' },";
			   }
			   if(signedTypeStr.endsWith(",")) signedTypeStr = signedTypeStr.substring(0,signedTypeStr.length()-1);
			   signedTypeStr += "]";
            }
            LOGGER.debug("--signedTypeStr:"+signedTypeStr);
            map.put("signedTypeStr", signedTypeStr);
            String meetingWayStr = "";
            if(meetingWay!=null) {
            	String[] ways=meetingWay.split(",");
            	meetingWayStr += "[";
            	for(int i=0;i<ways.length;i++) {
            		if("0".equals(ways[i])) {
            			meetingWayStr += "{ value: '0', text: '现场会议' },";
                	}else if("1".equals(ways[i])) {
                		meetingWayStr += "{ value: '1', text: '网络会议' },";
                	}else if("2".equals(ways[i])) {
                		meetingWayStr += "{ value: '2', text: '现场+网络' },";
                	}
            	}
            	if(meetingWayStr.endsWith(",")) meetingWayStr = meetingWayStr.substring(0,meetingWayStr.length()-1);
            	meetingWayStr += "]";
            }
            LOGGER.debug("--meetingWayStr:"+meetingWayStr);
            map.put("meetingWayStr", meetingWayStr);
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.debug("--getApplyRecordInfo---err-");
			map.put("success", false);
			map.put("content", "");
		}
		map.put("userName",user.getCnName());
		map.put("orgName",user.getOrgName());
		return ResponseResult.buildSuccessResult(map);
	}
	
	@ApiOperation(value = "保存会议室申请信息", notes = "保存会议室申请信息")
	@RequestMapping(value = "/editSaveWithoutNotice", method = RequestMethod.POST)
    public ResponseResult editSaveWithoutNotice(@ModelAttribute("message") String message, HttpServletRequest request) {
    	try {
			WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
		      
			Map<String, Object> map = JsonUtils.readValue(message);
			ApplyRecord entity = new ApplyRecord();
			String boardroomId = ValidateUtils.filter(StringUtils.null2String(map.get("boardroomId")));
			String startTimeStr = StringUtils.null2String(map.get("startTime"));
			String startTime = "";
			if (StringUtils.isNotEmpty(startTimeStr)) {
			    startTime = DateUtils.formatShortTime(new Date(Long.valueOf(startTimeStr)));
			}
            String endTimeStr =  StringUtils.null2String(map.get("endTime"));
            String endTime = "";
            if (StringUtils.isNotEmpty(endTimeStr)) {
                endTime = DateUtils.formatShortTime(new Date(Long.valueOf(endTimeStr)));
            }
			String meetingServe = StringUtils.null2String(map.get("meetingServe"));
			int isCycle = Integer.parseInt(StringUtils.null2String(map.get("isCycle")));
			int cycleType = Integer.parseInt(StringUtils.null2String(map.get("cycleType")));
			String cycleValue = StringUtils.null2String(map.get("cycleValue"));
			String cycleEndTime = StringUtils.null2String(map.get("cycleEndTime"));
			int isSync = Integer.parseInt(StringUtils.null2String(map.get("isSync")));
			entity.setBoardroomId(boardroomId);
			entity.setStartTime(startTime);
			entity.setEndTime(endTime);
			entity.setMeetingServe(meetingServe);
			entity.setIsCycle(isCycle);
			entity.setCycleType(cycleType);
			entity.setCycleValue(cycleValue);
			entity.setCycleEndTime(cycleEndTime);
			entity.setIsSync(isSync);
			List<Map<String, String>> cyclelist = null;
			String msg = "";
			if(StringUtils.isNotEmpty(boardroomId)) {
				//校验时间
				msg = this.boardroomSetService.checkTime(boardroomId,startTime, endTime,corpId);
			    if (StringUtils.isNotEmpty(msg)) {
			        return ResponseResult.buildFailureResult(msg);
			    }
			    //验证会议室在会议开始结束时间范围内是否已有会议
			    msg = this.applyRecordService.checkApplyRecordDate("",startTime, endTime,boardroomId, corpId);
			    if (StringUtils.isNotEmpty(msg)) {
			        return ResponseResult.buildFailureResult(msg);
			    }
			    //检测该会议室再周期内是否被占用
			    if(entity.getIsCycle() == 1) {
			    	cyclelist = this.applyRecordService.getCycleDateList(entity);
			    	msg = this.applyRecordService.checkCycleApplyRecordDate(entity, cyclelist, corpId);
			    	if (StringUtils.isNotEmpty(msg)) return ResponseResult.buildFailureResult(msg);
			    }
			}else {
				if(entity.getIsCycle() == 1) {
			    	cyclelist = this.applyRecordService.getCycleDateList(entity);
			    }
			}
			entity.setStatus(1);
			entity = this.applyRecordDingService.save(entity);
			if(entity.getIsCycle() == 1)  this.applyRecordService.saveCycleMeeting(entity, cyclelist, true);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseResult.buildFailureResult("保存失败");
		}
    	return ResponseResult.buildSuccessResult("保存成功");
    }
	
	@ApiOperation(value = "选择已预定周期会议室发起会议", notes = "选择已预定周期会议室发起会议")
	@RequestMapping(value = "/saveApplyBoardroomCycleMeeting", method = RequestMethod.POST)
    public ResponseResult saveApplyBoardroomCycleMeeting(@ModelAttribute("message") String message, HttpServletRequest request) {
    	try {
    		WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
			String token = user.getJwtToken();
			Map<String, Object> map = JsonUtils.readValue(message);
			String id =  StringUtils.null2String(map.get("id"));
			ApplyRecord	applyRecord = this.applyRecordDingService.findOne(id);
			String name =  StringUtils.null2String(map.get("name"));
 			int isSync = Integer.parseInt(StringUtils.null2String(map.get("isSync")));
 			applyRecord.setIsSync(isSync);
            int meetingWay = Integer.parseInt(StringUtils.null2String(map.get("meetingWay")));
 			applyRecord.setMeetingWay(meetingWay);
			// 会议名称
			applyRecord.setName(name);
			// 会议类型
			applyRecord.setMeetingTypeId(StringUtils.null2String(map.get("meetingType")));
			// 会议内容
			applyRecord.setContent(StringUtils.null2String(map.get("content")));
			//消息推送
			applyRecord.setMessagePush(StringUtils.null2String(map.get("messagePush")));
			//会议备注
			applyRecord.setRemark(StringUtils.null2String(map.get("remark")));
			//附件
			applyRecord.setFileId(StringUtils.null2String(map.get("fileId")));
			applyRecord.setStatus(1);
			// 会前提醒
			applyRecord.setIsNotice(Integer.valueOf(StringUtils.null2String(map.get("isNotice"))));
			// 提醒方式
			applyRecord.setNoticeType(StringUtils.null2String(map.get("noticeType")));
			// 提醒时间
			applyRecord.setNoticeTime(StringUtils.null2String(map.get("noticeTime")));
			// 会议签到
			String isSigned = StringUtils.null2String(map.get("isSigned"));
			applyRecord.setIsSigned(Integer.valueOf(isSigned));
			String signedType = "";
			if("1".equals(isSigned)){
				// 签到时间
				applyRecord.setSignedTime(StringUtils.null2String(map.get("signedTime")));
				signedType = StringUtils.null2String(map.get("signedType"));
				applyRecord.setSignedType(signedType);
				if("1".equals(signedType) || "2".equals(signedType)){
					applyRecord.setSignedRange(StringUtils.null2String(map.get("signedRange")));
				}
			}
			// 会议服务
			applyRecord.setMeetingServe(StringUtils.null2String(map.get("meetingServe")));
			// reason
			applyRecord.setReason("");
			// 主持人
			String emceeUserJsonStr = StringUtils.null2String(map.get("jsonStrEmceeUser"));
			String emceeUser = StringUtils.null2String(applyRecord.getEmceeUser());
			if ("".equals(emceeUser)) {
			    emceeUser = UuidUtils.UUID();
			    applyRecord.setEmceeUser(emceeUser);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", emceeUser, emceeUserJsonStr,
			        "oa_meeting_apply_record", "emcee_user");
			// 纪要员
			String memoUserJsonStr = StringUtils.null2String(map.get("jsonStrMemoUser"));
			String memoUser = StringUtils.null2String(applyRecord.getMemoUser());
			if ("".equals(memoUser)) {
			    memoUser = UuidUtils.UUID();
			    applyRecord.setMemoUser(memoUser);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", memoUser, memoUserJsonStr,
			        "oa_meeting_apply_record", "memo_user");
			// 参会人
			String attendUserJsonStr = StringUtils.null2String(map.get("jsonStrAttendUser"));
			String attendUser = StringUtils.null2String(applyRecord.getAttendUser());
			if ("".equals(attendUser)) {
			    attendUser = UuidUtils.UUID();
			    applyRecord.setAttendUser(attendUser);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendUser, attendUserJsonStr,
			        "oa_meeting_apply_record", "attend_user");
			
			// 会议列席人
		    String attendantsJsonStr = StringUtils.null2String(request.getParameter("jsonStrAttendants"));
		    String attendants = StringUtils.null2String(applyRecord.getMeetingAttendants());
		    if ("".equals(attendants)) {
		    	attendants = UuidUtils.UUID();
		    	applyRecord.setMeetingAttendants(attendants);
		    }
		    this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendants, attendantsJsonStr,
	                "oa_meeting_apply_record", "meeting_attendants");
		    
			String cycleId = applyRecord.getCycleId();
			//查询还未使用的周期会议室
			List<ApplyRecord> arCycleList = this.applyRecordService.getApplyRecordListByCycleId(cycleId, corpId);
			if(CollectionUtils.isNotEmpty(arCycleList)) {
				for(ApplyRecord a : arCycleList) {
					this.applyRecordService.applyRecordCopy(a, applyRecord);
				}
			}
			List<ApplyRecord> resultList = this.applyRecordService.save(arCycleList);
			if(CollectionUtils.isNotEmpty(resultList)) {
				ApplyRecord ar = arCycleList.get(0);
				List<String> newUserIdList = this.applyRecordService.getApplyRecordUserList(ar, TOKEN);
				//会议签到地址
				String signType = ar.getSignedType();
				if(ar.getIsSigned()==1 && ("1".equals(signType)||"2".equals(signType))){
					String addrListJson = StringUtils.null2String(map.get("addrList"));
					this.signedAddressService.saveSignedAddress(ar.getId(), addrListJson);
				}
				
			    //保存周期会议
			    if(ar.getIsCycle() == 1) {
			    	CycleMeetingThread cycThread = new CycleMeetingThread(resultList, newUserIdList, "", corpId, ar.getIsSigned());
			    	cycThread.start();
			    }
			    String applyRecordId = ar.getId();
			    Map<String, Object> ds = new HashMap<>();
			    ds.put("applyRecordId", applyRecordId);
				ds.put("meetingTitle", ar.getName());
				ds.put("startTime", ar.getStartTime());
				BoardroomSet room = this.boardroomSetService.findOne(ar.getBoardroomId());
				ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(ar.getAddress()) ? ar.getAddress():"无") : room.getAddress());
			    String noticeUserId = ar.getCreatedBy();
			    String userName = "";
			    if(StringUtils.isNotEmpty(noticeUserId)){
			        Map<String, Object> userInfo = this.userApiService.getUser(noticeUserId, corpId,  "", TOKEN);
			        if(userInfo != null){
			            userName = StringUtils.null2String(userInfo.get("userName"));
			        }
			    }
				ds.put("userId", noticeUserId);
				ds.put("userName", userName);
				ds.put("userOrg", ar.getCreatedOrg());
				ds.put("type", "2");
				boolean mobilePush = false;
			    boolean emailPush = false;
			    boolean smsPublish = false;
				String mesgPush = ar.getMessagePush();
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
				if(CollectionUtils.isNotEmpty(newUserIdList)) sendMessageToUser(emailPush, mobilePush, smsPublish, newUserIdList, ds, corpId, token, request);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseResult.buildFailureResult("保存失败");
		}
    	return ResponseResult.buildSuccessResult("保存成功");
    }
	
	@ApiOperation(value = "保存会议申请信息", notes = "保存会议申请信息")
	@RequestMapping(value = "/saveInfo", method = RequestMethod.POST)
	public ResponseResult saveInfo(HttpServletRequest request, @RequestParam("message") String message) {
		try {
			WebUser user = WebUtils.getCurrentUser();
			String token = "";
			String corpId = "";
			String userId = "";
			if(user != null){
				corpId = user.getCorpId();
				userId = user.getUserId();
				token = user.getJwtToken();
			}
			BoardroomSet room = null;
			Map<String, Object> map = JsonUtils.readValue(message);
			
			boolean isEdit = false;
			ApplyRecord applyRecord = null;
			ApplyRecord oldApplyRecord = null;
			
			int oldMeetingWay = 0;
			String oldcreateBy = "";
			
			String id =  StringUtils.null2String(map.get("id"));
			if (StringUtils.isNotEmpty(id)) {
				applyRecord = this.applyRecordDingService.findOne(id);
				if (applyRecord == null) {
					applyRecord = new ApplyRecord();
				}
				oldMeetingWay = applyRecord.getMeetingWay();
				oldcreateBy = applyRecord.getCreatedBy();
				
				oldApplyRecord = this.applyRecordCopy(applyRecord);//用于判断会议信息是否修改

				if(applyRecord.getIsSync() == 1 && StringUtils.isNotEmpty(applyRecord.getName())) {
					isEdit = true;
				}
			} else {
				applyRecord = new ApplyRecord();
			}
			if(!"".equals(StringUtils.null2String(map.get("meetingPeopleNum")))) {
				applyRecord.setMeetingPeopleNum(Integer.valueOf(StringUtils.null2String(map.get("meetingPeopleNum"))));
			}
			
			if(!"".equals(StringUtils.null2String(map.get("isSyncCalendar")))) {
				applyRecord.setIsSyncCalendar(Integer.valueOf(StringUtils.null2String(map.get("isSyncCalendar"))));
			}
			
			if("".equals(StringUtils.null2String(applyRecord.getId()))){
				applyRecord.setCreatedBy(userId);
				applyRecord.setCorpId(corpId);
			}else{
				applyRecord.setLastModifiedBy(userId);
			}
			//会议创建人
			applyRecord.setCreatedBy(userId);
			//会议单位
			applyRecord.setCorpId(corpId);
	        //保存前 验证
	        // 验证名称
			String name =  StringUtils.null2String(map.get("name"));
			/*msg = this.applyRecordDingService.checkApplyRecordInfo(id, name, 1, corpId);
			if (StringUtils.isNotEmpty(msg)) {
	            return OperationResult.buildFailureResult(msg);
			}*/
			// 会议结束时间
			String startTimeStr = StringUtils.null2String(map.get("startTime"));
			String startTime = "";
			if (StringUtils.isNotEmpty(startTimeStr)) {
			    startTime = DateUtils.formatShortTime(new Date(Long.valueOf(startTimeStr)));
			}
            String endTimeStr =  StringUtils.null2String(map.get("endTime"));
            String endTime = "";
            if (StringUtils.isNotEmpty(endTimeStr)) {
                endTime = DateUtils.formatShortTime(new Date(Long.valueOf(endTimeStr)));
            }
            String  boardroomId =  StringUtils.null2String(map.get("boardroomId"));
            // 会议开始时间
 			applyRecord.setStartTime(startTime);
 			// 会议结束时间
            applyRecord.setEndTime(endTime);
            int isCycle = Integer.parseInt(StringUtils.null2String(map.get("isCycle")));
 			// 周期性会议
 			applyRecord.setIsCycle(isCycle);
 			if(isCycle == 1) {
 				// 重复方式
 				applyRecord.setCycleType(Integer.parseInt(StringUtils.null2String(map.get("cycleType"))));
 				//周期值
 				applyRecord.setCycleValue(StringUtils.null2String(map.get("cycleValue")));
 				// 周期结束时间
 				applyRecord.setCycleEndTime(StringUtils.null2String(map.get("cycleEndTime")));
 			}
 			int isSync = Integer.parseInt(StringUtils.null2String(map.get("isSync")));
 			applyRecord.setIsSync(isSync);
 			List<Map<String, String>> cyclelist = null;
 			// 会议室id
 			applyRecord.setBoardroomId(boardroomId);
 			String msg = "";
            if(!isEdit && StringUtils.isNotEmpty(boardroomId)) {
            	//验证会议开始结束时间是否在会议室的范围内
            	msg = this.boardroomSetService.checkTime(boardroomId,startTime, endTime,corpId);
                if (StringUtils.isNotEmpty(msg)) {
                	return ResponseResult.buildFailureResult(msg);
                }
                //验证会议室在会议开始结束时间范围内是否已有会议
    	        msg = this.applyRecordDingService.checkApplyRecordDate(id,startTime, endTime,boardroomId, corpId);
    	        if (StringUtils.isNotEmpty(msg)) {
    	        	return ResponseResult.buildFailureResult(msg);
    	        }
    	        //检测该会议室在周期内是否被占用
    	        if(applyRecord.getIsCycle() == 1) {
    	        	cyclelist = this.applyRecordService.getCycleDateList(applyRecord);
    	        	msg = this.applyRecordService.checkCycleApplyRecordDate(applyRecord, cyclelist, corpId);
    	        	if (StringUtils.isNotEmpty(msg))  return ResponseResult.buildFailureResult(msg);
    	        }
    	        //验证会议室是否审批
    	        room = this.boardroomSetService.findOne(boardroomId);
            }else {
            	if(applyRecord.getIsCycle() == 1) {
    	        	cyclelist = this.applyRecordService.getCycleDateList(applyRecord);
    	        }
            }
            applyRecord.setStatus(1);
            int meetingWay = Integer.parseInt(StringUtils.null2String(map.get("meetingWay")));
 			applyRecord.setMeetingWay(meetingWay);
			// 会议名称
			applyRecord.setName(name);
			// 会议类型
			applyRecord.setMeetingTypeId(StringUtils.null2String(map.get("meetingType")));
			// 会议内容
			applyRecord.setContent(StringUtils.null2String(map.get("content")));
			// 自定义会议地址
			applyRecord.setAddress(StringUtils.null2String(map.get("address")));
			//消息推送
			applyRecord.setMessagePush(StringUtils.null2String(map.get("messagePush")));
			//会议备注
			applyRecord.setRemark(StringUtils.null2String(map.get("remark")));
			//附件
			applyRecord.setFileId(StringUtils.null2String(map.get("fileId")));
			// 主持人
			String emceeUserJsonStr = StringUtils.null2String(map.get("jsonStrEmceeUser"));
			String emceeUser = StringUtils.null2String(applyRecord.getEmceeUser());
			if ("".equals(emceeUser)) {
				emceeUser = UuidUtils.UUID();
				applyRecord.setEmceeUser(emceeUser);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", emceeUser, emceeUserJsonStr,
					"oa_meeting_apply_record", "emcee_user");
			// 纪要员
			String memoUserJsonStr = StringUtils.null2String(map.get("jsonStrMemoUser"));
			String memoUser = StringUtils.null2String(applyRecord.getMemoUser());
			if ("".equals(memoUser)) {
				memoUser = UuidUtils.UUID();
				applyRecord.setMemoUser(memoUser);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", memoUser, memoUserJsonStr,
					"oa_meeting_apply_record", "memo_user");
			// 参会人
			String attendUserJsonStr = StringUtils.null2String(map.get("jsonStrAttendUser"));
			String attendUser = StringUtils.null2String(applyRecord.getAttendUser());
			if ("".equals(attendUser)) {
				attendUser = UuidUtils.UUID();
				applyRecord.setAttendUser(attendUser);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendUser, attendUserJsonStr,
					"oa_meeting_apply_record", "attend_user");
			// 会议列席人
			String attendantsJsonStr = StringUtils.null2String(map.get("jsonStrAttendants"));
			String attendants = StringUtils.null2String(applyRecord.getMeetingAttendants());
			if ("".equals(attendants)) {
				attendants = UuidUtils.UUID();
				applyRecord.setMeetingAttendants(attendants);
			}
			this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendants, attendantsJsonStr,
					"oa_meeting_apply_record", "meeting_attendants");

			// 会前提醒
			applyRecord.setIsNotice(Integer.valueOf(StringUtils.null2String(map.get("isNotice"))));
			// 提醒方式
			applyRecord.setNoticeType(StringUtils.null2String(map.get("noticeType")));
			// 提醒时间
			applyRecord.setNoticeTime(StringUtils.null2String(map.get("noticeTime")));
			
			// 会议签到
			String isSigned = StringUtils.null2String(map.get("isSigned"));
			applyRecord.setIsSigned(Integer.valueOf(isSigned));
			String signedType = "";
			if("1".equals(isSigned)){
				// 签到时间
				applyRecord.setSignedTime(StringUtils.null2String(map.get("signedTime")));
				signedType = StringUtils.null2String(map.get("signedType"));
				applyRecord.setSignedType(signedType);
				if("1".equals(signedType) || "2".equals(signedType)){
					applyRecord.setSignedRange(StringUtils.null2String(map.get("signedRange")));
				}
			}
			
			// 会议服务
			applyRecord.setMeetingServe(StringUtils.null2String(map.get("meetingServe")));
			// reason
			applyRecord.setReason("");
			
			//设置一些判断会议信息是否有修改得变量
			String addrListJson = StringUtils.null2String(map.get("addressList"));
	        boolean meetingInfoIsChange = false;
	        List<String> oldUserIdList = null;
	        if(isEdit) {
	        	String deleteId = StringUtils.null2String(map.get("deleteId"));
	        	//编辑时，会议室有变更的话
				this.applyRecordService.changeBoardroom(applyRecord, oldApplyRecord, deleteId);
	        	meetingInfoIsChange = isEntityChanged(applyRecord, id, oldApplyRecord, addrListJson, corpId);
	        	oldUserIdList = this.applyRecordService.getApplyRecordUserList(applyRecord, TOKEN);
	        }

			
			LOGGER.debug("tMeetingWay："+meetingWay);
			//修改后是网络会议
			boolean newIsWeb = false;
			if(meetingWay==1 || meetingWay==2) {
				newIsWeb = true;
			}
			LOGGER.debug("newIsWeb："+newIsWeb);
			//修改会议通知
			if(StringUtils.isNotEmpty(id)) {
				
				LOGGER.debug("oldMeetingWay："+oldMeetingWay);
				//修改前是网络会议
				boolean oldIsWeb = false;
				if(oldMeetingWay==1 || oldMeetingWay==2) {
					oldIsWeb = true;
				}
				LOGGER.debug("oldIsWeb："+oldIsWeb);
				if(newIsWeb) {
					if(oldIsWeb) {
						//修改全时
						String qsDesp = qsMeetingService.updateQSMeeting(id,applyRecord,oldcreateBy,user.getJwtToken());
						if(!"0".equals(qsDesp)) {
							return ResponseResult.buildFailureResult(qsDesp);
						}
						//保存
						applyRecord = this.applyRecordDingService.save(applyRecord);
					}else {
						//新增
						Map _map = qsMeetingService.newQSMeeting(applyRecord.getName(),
								                                applyRecord.getStartTime(),
								                                applyRecord.getEndTime(),
								                                userId,
								                                user.getJwtToken());
						String success = _map.get("success")+"";
						if("0".equals(success)) {
							//成功 保存主表数据
							applyRecord = this.applyRecordDingService.save(applyRecord);
							QSMeetingInfo info = (QSMeetingInfo) _map.get("info");
							//保存全时会议信息
							//String emceeUserId = this.applyRecordService.getEmceeUser(applyRecord);
							info.setMeetingApplyId(applyRecord.getId());
							info.setEmceeUser(applyRecord.getCreatedBy());
							qsMeetingService.saveQSMeetingInfo(info);
						}else {
							return ResponseResult.buildFailureResult((String)_map.get("msg"));
						}
						
						
					}
				}else {
					if(oldIsWeb) {
						//取消
						qsMeetingService.delQSMeeting(id,oldcreateBy,user.getJwtToken());
					}
					//保存
					applyRecord = this.applyRecordDingService.save(applyRecord);
				}
			}else {
				//新增 网络会议  开全时会议
				if(newIsWeb) {

					Map _map = qsMeetingService.newQSMeeting(applyRecord.getName(),
									                            applyRecord.getStartTime(),
									                            applyRecord.getEndTime(),
									                            userId,
									                            user.getJwtToken());
					String success = _map.get("success")+"";
					LOGGER.debug("success："+success);
					if("0".equals(success)) {
						//成功 保存主表数据
						applyRecord = this.applyRecordDingService.save(applyRecord);
						QSMeetingInfo info = (QSMeetingInfo) _map.get("info");
						//保存全时会议信息
						//String emceeUserId = this.applyRecordService.getEmceeUser(applyRecord);
						//LOGGER.debug("emceeUserId："+emceeUserId);
						LOGGER.debug("applyRecord.getId()："+applyRecord.getId());
						info.setMeetingApplyId(applyRecord.getId());
						info.setEmceeUser(applyRecord.getCreatedBy());
						qsMeetingService.saveQSMeetingInfo(info);
					}else {
						return ResponseResult.buildFailureResult((String) _map.get("msg"));
					}
				}else {
					//非网络会议
					//保存
					applyRecord = this.applyRecordDingService.save(applyRecord);
				}
				
			}
			
			//记录新建日志
	        if(StringUtils.isEmpty(id) && logService.checkOptLog(corpId, "meeting:start:02", TOKEN)) {//判断是否记录日志
	        	this.logService.saveModuleLog("meeting:start:02", applyRecord.getName(), "");  
	        }
			String recordId = "";
			if(applyRecord != null){
				recordId = StringUtils.null2String(applyRecord.getId());
			}
			LOGGER.debug("--recordId:"+recordId);
			if(!"".equals(recordId)){
				List<String> newUserIdList = this.applyRecordService.getApplyRecordUserList(applyRecord, TOKEN);
	        	List<String> addList = null;
	        	List<String> noticeUpdateList = null;
				//需定位签到
				if("1".equals(isSigned) && ("1".equals(signedType) || "2".equals(signedType))){
	        		this.signedAddressService.saveSignedAddress(recordId, addrListJson);
				}
    			
//				if(!"0".equals(isApprove)){
//					List<String> scopeList = new ArrayList<String>();
//	    			scopeList.add(room.getAdminUserScope());
//	    			List<MeetingScope> msList = this.meetingScopeService.getMeetingScopeList("oa_meeting_boardroom_set",
//	    					"admin_user_scope", scopeList, true);
//	    			if (msList != null && msList.size()>0) {
//	    				// 推送申请---会议室管理员
//	    				this.noticeInfoService.saveNoticeInfoIsApply(applyRecord, msList);
//	    			}
//				}else{
					//this.applyRecordDingService.editApplyRecordInfo(applyRecord.getId(),"1","", "",token);
				
					if(isEdit) {
	        			addList = new ArrayList<String>();
	                	noticeUpdateList = new ArrayList<String>();
	                	//获取新增加的参会人id
	        			for(String newId : newUserIdList) {
	        				if(!oldUserIdList.contains(newId)) {
	        					addList.add(newId);
	        				}
	        			}
	        			//获取已参加的人id
	        			for(String oldId : oldUserIdList) {
	        				if(newUserIdList.contains(oldId)) {
	        					noticeUpdateList.add(oldId);
	        				}
	        			}
	    				this.noticeInfoService.deleteNoticeInfoByApplyrecordId(id, corpId);
	    				this.noticeTurnoverService.deleteNoticeTurnover(id, corpId);
	        			this.signedInfoService.deleteSignedInfoByApplyrecordId(id, corpId);
					}
	    			//新建会议通知数据
	    			this.noticeInfoService.addNoticeInfo(newUserIdList, recordId, corpId);
	                //新建会议签到数据
	                if("1".equals(isSigned)) this.signedInfoService.addSignedInfo(newUserIdList, recordId, corpId);
	                //保存周期会议
	                if(applyRecord.getIsCycle() == 1) {
	                	List<ApplyRecord> arCycleList = this.applyRecordService.saveCycleMeeting(applyRecord, cyclelist);
	                	CycleMeetingThread cycThread = new CycleMeetingThread(arCycleList, newUserIdList, applyRecord.getId(), corpId, applyRecord.getIsSigned());
	                	cycThread.start();
	                }
//				}
        		// 新建编辑会议发送会议申请通知
	            Map<String, Object> ds = new HashMap<>();
	            ds.put("applyRecordId", recordId);
	    		ds.put("meetingTitle", applyRecord.getName());
	    		ds.put("startTime", applyRecord.getStartTime());
	    		ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(applyRecord.getAddress()) ? applyRecord.getAddress():"无") : room.getAddress());
	            String noticeUserId = applyRecord.getCreatedBy();
	            String sendUserName = "";
	            if(StringUtils.isNotEmpty(noticeUserId)){
	                Map<String, Object> userInfo = this.userApiService.getUser(noticeUserId, corpId,  "", TOKEN);
	                if(userInfo != null){
	                	sendUserName = StringUtils.null2String(userInfo.get("userName"));
	                }
	            }
	    		ds.put("userId", noticeUserId);
	    		ds.put("userName", sendUserName);
	    		ds.put("userOrg", applyRecord.getCreatedOrg());
	    		ds.put("type", "2");
	    		boolean mobilePush = false;
	            boolean emailPush = false;
	            boolean smsPublish = false;
				String mesgPush = applyRecord.getMessagePush();
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
	        	if(isEdit) {
	        		//新增的参会人员发送邀请通知
	        		if(CollectionUtils.isNotEmpty(addList)) sendMessageToUser(emailPush, mobilePush, smsPublish, addList, ds, corpId, token, request);
	        		//已参会人员发送变更通知
	        		if(CollectionUtils.isNotEmpty(noticeUpdateList) && meetingInfoIsChange) {
	        			ds.put("type", "9");
	        			sendMessageToUser(emailPush, mobilePush, smsPublish, noticeUpdateList, ds, corpId, token, request);
	        		}
	        	}else {
	        		if(CollectionUtils.isNotEmpty(newUserIdList)) sendMessageToUser(emailPush, mobilePush, smsPublish, newUserIdList, ds, corpId, token, request);
	        	}

			}
		} catch (Exception e) {
			LOGGER.debug("--err:"+e.getMessage());
			e.printStackTrace();
			return ResponseResult.buildFailureResult("保存会议申请失败");
		}
		return ResponseResult.buildSuccessResult("保存会议申请成功");
	}
	
	/**
     * 发送消息通知
     * @param userIdList
     * @param ds
     * @param corpId
     * @param request
     */
    private void sendMessageToUser(boolean emailPush, boolean mobilePush, boolean smsPublish, List<String> userIdList, Map<String, Object> ds, String corpId, String token, HttpServletRequest request) {
    	StringBuffer ids = new StringBuffer();
		StringBuffer jsonIds = new StringBuffer("[");
		for(int i = 0; i < userIdList.size(); i++) {
			if(i == userIdList.size() - 1) {
				ids.append(userIdList.get(i));
				jsonIds.append("{\"10\":\"" + userIdList.get(i) + "\"}]");
			}else {
				ids.append(userIdList.get(i) + ",");
				jsonIds.append("{\"10\":\"" + userIdList.get(i) + "\"},");
			}
		}
		jsonIds.append("]");
		ds.put("userIds", ids.toString());
		ds.put("orgIds", "");
		if(!"".equals(ids.toString())) {
			this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, token);
			this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, token, request);
			this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, token);
		}
		if(!"[]".equals(jsonIds.toString())) this.meetingSendMsgUtils.sendMessage(ds, jsonIds.toString(), corpId, token);
    }
    
    /**
     * 判断会议信息是否修改
     * @param newEntity
     * @param addrListJson
     * @param corpId
     * @return
     */
    private boolean isEntityChanged(ApplyRecord newEntity, String id, ApplyRecord oldEntity, String addrListJson, String corpId) {
    	List<SignedAddress> saOldList = this.signedAddressService.findByRecordId(newEntity.getId());
    	List<Map<String, String>> addrList = null;
		if(!"".equals(addrListJson)) {
			addrList = JsonUtils.readListValue(addrListJson);
		}
    	List<SignedAddress> saNewList = null;
    	if(CollectionUtils.isNotEmpty(addrList)) {
    		saNewList = new ArrayList<SignedAddress>();
    		for(Map<String, String> m : addrList) {
    			SignedAddress sa = new SignedAddress();
    			sa.setLongitude(m.get("lng"));
    			sa.setLatitude(m.get("lat"));
    			sa.setSignedAddress(m.get("address"));
    			saNewList.add(sa);
    		}
    	}
    	boolean sAddressIsSame = true;
    	if(CollectionUtils.isNotEmpty(saOldList) && CollectionUtils.isNotEmpty(saNewList)) {
    		if(!saOldList.equals(saNewList)) {
    			sAddressIsSame = false;
    		}
    	}else if((CollectionUtils.isEmpty(saOldList) && CollectionUtils.isNotEmpty(saNewList)) || 
    			(CollectionUtils.isNotEmpty(saOldList) && CollectionUtils.isEmpty(saNewList))){
    		sAddressIsSame = false;
    	}
    	if(oldEntity.equals(newEntity) && sAddressIsSame) return false;
    	else return true;
    }
	
	private ApplyRecord applyRecordCopy(ApplyRecord applyRecord) {
		ApplyRecord newEntity = new ApplyRecord();
		if(applyRecord != null) {
			String name = applyRecord.getName();
			if(name != null) newEntity.setName(name);
			String content = applyRecord.getContent();
			if(content != null) newEntity.setContent(content);
			String boardRoomId = applyRecord.getBoardroomId();
			if(boardRoomId != null) newEntity.setBoardroomId(boardRoomId);
			String startTime = applyRecord.getStartTime();
			if(startTime != null) newEntity.setStartTime(startTime);
			String endTime = applyRecord.getEndTime();
			if(endTime != null) newEntity.setEndTime(endTime);
			newEntity.setIsSigned(applyRecord.getIsSigned());
			String signedTime = applyRecord.getSignedTime();
			if(signedTime != null) newEntity.setSignedTime(signedTime);
			String signedType = applyRecord.getSignedType();
			if(signedType != null) newEntity.setSignedType(signedType);
			String signedRange = applyRecord.getSignedRange();
			if(signedRange != null) newEntity.setSignedRange(signedRange);
			String remark = applyRecord.getRemark();
			if(remark != null) newEntity.setRemark(remark);
		}
		return newEntity;
	}
	
    /**
     * 查询与我有关的周期会议
     */
    @ApiOperation(value="查询已预定会议室list", notes="查询已预定会议室list")
    @RequestMapping(value="/applyBoardroomList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getApplyBoardroomList(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition"); 
            String userId = user.getUserId();
            String corpId = user.getCorpId();
            List<Map> list = this.applyRecordDingService.findApplyBoardroomListByPage(currentPage, pageSize, userId, corpId, condition);
            resultMap.put("data", list);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
            
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    @ApiOperation(value="删除已预定但未召开会议室数据", notes="删除已预定但未召开会议室数据")
    @RequestMapping(value="/deleteApplyBoardroom", method=RequestMethod.POST, produces={"application/json; charset=UTF-8"})
    public ResponseResult deleteApplyBoardroom(HttpServletRequest request) {
    	try {
			String id = StringUtils.null2String(request.getParameter("id"));
			ApplyRecord entity = applyRecordDingService.findOne(id);
			if(entity != null && entity.getIsSync() == 1) {
				return ResponseResult.buildFailureResult("已使用会议室无法删除");
			}
			applyRecordDingService.delete(entity);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseResult.buildFailureResult("取消失败");
		}
    	return ResponseResult.buildSuccessResult("取消成功");
    }
    
    @ApiOperation(value="查询可以使用的会议室列表数据", notes="查询可以使用的会议室列表数据")
    @RequestMapping(value="/canUseBoardroomList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    public ResponseResult findCanUseBoardroomListByPage(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition"); 
            String isCycle = request.getParameter("isCycle"); 
            String userId = user.getUserId();
            String corpId = user.getCorpId();
            List<Map> list = this.applyRecordDingService.findCanUseBoardroomListByPage(currentPage, pageSize, userId, isCycle, corpId, condition);
            resultMap.put("data", list);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
	@ApiOperation(value = "流程提交后处理各个数据", notes = "保存会议状态和会议选人数据")
	@RequestMapping(value = "/saveInfoAfterBpm", method = RequestMethod.POST)
	public ResponseResult saveInfoAfterBpm(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
		String token = user.getJwtToken();
		String corpId = user.getCorpId();
		String userId = user.getUserId();

        String id =  StringUtils.null2String(request.getParameter("id"));
        String jsonStrEmceeUser =  StringUtils.null2String(request.getParameter("jsonStrEmceeUser"));
        String jsonStrMemoUser =  StringUtils.null2String(request.getParameter("jsonStrMemoUser"));
        String jsonStrAttendUser =  StringUtils.null2String(request.getParameter("jsonStrAttendUser"));
        String jsonStrAttendants =  StringUtils.null2String(request.getParameter("jsonStrAttendants"));
        String nStatus =  StringUtils.null2String(request.getParameter("status"));
        Map<String, String> jsonMap = new HashMap<>();
        jsonMap.put("jsonStrEmceeUser", jsonStrEmceeUser);
        jsonMap.put("jsonStrMemoUser", jsonStrMemoUser);
        jsonMap.put("jsonStrAttendUser", jsonStrAttendUser);
        jsonMap.put("jsonStrAttendants", jsonStrAttendants);
        String jsonStr = JSONUtils.toJSONString(jsonMap);
        try {
			ApplyRecord applyRecord = this.applyRecordDingService.findOne(id);
			if(applyRecord != null){
				//状态修改
				int status = applyRecord.getStatus();
				if(status != 1){
					if("4".equals(nStatus) || "6".equals(nStatus)){//提交
						applyRecord.setStatus(0);
					}else if("1".equals(nStatus)){//正常结束
						applyRecord.setStatus(1);
					}else if("5".equals(nStatus)){//保存到草稿箱
						applyRecord.setStatus(6);
					}
				}
				Map<String, Object> map = new HashMap<>();
				if(StringUtils.isNotEmpty(jsonStr)){
					map = JsonUtils.readValue(jsonStr);
				}
				// 主持人
				String emceeUserJsonStr = StringUtils.null2String(map.get("jsonStrEmceeUser"));
				String emceeUser = StringUtils.null2String(applyRecord.getEmceeUser());
				if ("".equals(emceeUser)) {
					emceeUser = UuidUtils.UUID();
					applyRecord.setEmceeUser(emceeUser);
				}
				this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", emceeUser, emceeUserJsonStr,
						"oa_meeting_apply_record", "emcee_user");
				// 纪要员
				String memoUserJsonStr = StringUtils.null2String(map.get("jsonStrMemoUser"));
				String memoUser = StringUtils.null2String(applyRecord.getMemoUser());
				if ("".equals(memoUser)) {
					memoUser = UuidUtils.UUID();
					applyRecord.setMemoUser(memoUser);
				}
				this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", memoUser, memoUserJsonStr,
						"oa_meeting_apply_record", "memo_user");
				// 参会人
				String attendUserJsonStr = StringUtils.null2String(map.get("jsonStrAttendUser"));
				String attendUser = StringUtils.null2String(applyRecord.getAttendUser());
				if ("".equals(attendUser)) {
					attendUser = UuidUtils.UUID();
					applyRecord.setAttendUser(attendUser);
				}
				this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendUser, attendUserJsonStr,
						"oa_meeting_apply_record", "attend_user");
				// 会议列席人
			    String attendantsJsonStr = StringUtils.null2String(request.getParameter("jsonStrAttendants"));
			    String attendants = StringUtils.null2String(applyRecord.getMeetingAttendants());
			    if ("".equals(attendants)) {
			    	attendants = UuidUtils.UUID();
			    	applyRecord.setMeetingAttendants(attendants);
			    }
			    this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", attendants, attendantsJsonStr,
		                "oa_meeting_apply_record", "meeting_attendants");
			    
				//改变提醒方式默认值
				int isNotice = applyRecord.getIsNotice();
				if(isNotice == 1){
					applyRecord.setNoticeType("2");
				}

				this.applyRecordDingService.save(applyRecord);
				//地址
				List<SignedAddress> list = this.signedAddressService.findByFkid(id);
				if(list!=null && list.size()>0){
					for(int i=0; i<list.size(); i++){
						SignedAddress address = list.get(i);
						if(address!=null && StringUtils.isEmpty(address.getApplyRecordId())){
							address.setApplyRecordId(address.getFkid());
						}
					}
					this.signedAddressService.save(list);
				}
				//推送
				if("1".equals(nStatus)){
					/*String userId = StringUtils.null2String(request.getParameter("userId"));
					String userName = StringUtils.null2String(request.getParameter("userName"));*/
					this.applyRecordDingService.editApplyRecordInfo(applyRecord.getId(),"1","", "",token);
					//保存周期会议
		            if(applyRecord.getIsCycle() == 1) {
		            	List<String> newUserIdList = this.applyRecordService.getApplyRecordUserList(applyRecord, token);
		            	List<Map<String, String>> cyclelist = this.applyRecordService.getCycleDateList(applyRecord);
		            	List<ApplyRecord> arCycleList = this.applyRecordService.saveCycleMeeting(applyRecord, cyclelist);
		            	CycleMeetingThread cycThread = new CycleMeetingThread(arCycleList, newUserIdList, applyRecord.getId(), corpId, applyRecord.getIsSigned());
		            	cycThread.start();
		            }
					BoardroomSet room = null;
					if(StringUtils.isNotEmpty(applyRecord.getBoardroomId())) {
						room = this.boardroomSetService.findOne(applyRecord.getBoardroomId());
					}
					// 新建编辑会议发送会议申请通知
					int nStauts = applyRecord.getStatus();
					String userIds = "", orgIds = "", jsonIds = "[";
					Map<String, Object> ds = new HashMap<>();
					ds.put("applyRecordId", id);
					ds.put("meetingTitle", applyRecord.getName());
					ds.put("startTime", applyRecord.getStartTime());
					ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(applyRecord.getAddress()) ? applyRecord.getAddress():"无") : room.getAddress());
					String noticeUserId = applyRecord.getCreatedBy();
					String userName = "";
					if(StringUtils.isNotEmpty(noticeUserId)){
						Map<String, Object> userInfo = this.userApiService.getUser(noticeUserId, corpId,  "", token);
						if(userInfo != null){
							userName = StringUtils.null2String(userInfo.get("userName"));
						}
					}
					ds.put("userId", noticeUserId);
					ds.put("userName", userName);
					ds.put("userOrg", applyRecord.getCreatedOrg());
					if(nStauts == 1){//正常结束
						ds.put("type", "2");
						List<String> userIdList = this.applyRecordService.getApplyRecordUserList(applyRecord, token);
						if(applyRecord.getIsSync()==1 && applyRecord.getIsCycle() != 1) {
							//新建会议通知数据
			    			this.noticeInfoService.addNoticeInfo(userIdList, id, corpId);
						}
						
						if(CollectionUtils.isNotEmpty(userIdList)){
	        				StringBuffer ids = new StringBuffer();
	        				StringBuffer jsonIdsBuffer = new StringBuffer("[");
	        				for(int i = 0; i < userIdList.size(); i++) {
	        					if(i == userIdList.size() - 1) {
	        						ids.append(userIdList.get(i));
	        						jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"}]");
	        					}else {
	        						ids.append(userIdList.get(i) + ",");
	        						jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"},");
	        					}
	        				}
	        				jsonIdsBuffer.append("]");
	        				userIds = ids.toString();
	        				jsonIds = jsonIdsBuffer.toString();
						}
						
						//----全时会议处理--start
						int meetingWay = applyRecord.getMeetingWay();
						LOGGER.debug("tMeetingWay："+meetingWay);

						boolean newIsWeb = false;
						if(meetingWay==1 || meetingWay==2) {
							newIsWeb = true;
						}
						LOGGER.debug("newIsWeb："+newIsWeb);
						
						if(newIsWeb) {
							
							//新增
							Map qs_map = qsMeetingService.newQSMeeting(applyRecord.getName(),
																	applyRecord.getStartTime(),
																	applyRecord.getEndTime(),
																	applyRecord.getCreatedBy(),
						                                            user.getJwtToken());
							String success = qs_map.get("success")+"";
							if("0".equals(success)) {

								QSMeetingInfo info = (QSMeetingInfo) qs_map.get("info");
								//保存全时会议信息
								//String emceeUserId = this.service.getEmceeUser(applyRecord);
								info.setMeetingApplyId(applyRecord.getId());
								info.setEmceeUser(applyRecord.getCreatedBy());
								qsMeetingService.saveQSMeetingInfo(info);
							}else {
								String msg = (String) qs_map.get("msg");
								LOGGER.error(msg);
							}
		
						}
						//----全时会议处理--end
						
					}
					if(!StringUtils.isEmpty(userIds)){
						boolean mobilePush = false;
			            boolean emailPush = false;
			            boolean smsPublish = false;
						String mesgPush = applyRecord.getMessagePush();
						if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
						if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
						if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
						ds.put("userIds", userIds);
						ds.put("orgIds", orgIds);
						this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, token);
						this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, token, request);
						this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, token);
					}
					if(StringUtils.isNotEmpty(jsonIds) || !"[]".equals(jsonIds)){
						this.meetingSendMsgUtils.sendMessage(ds, jsonIds, corpId, token);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseResult.buildFailureResult("保存会议失败");
		}
		return ResponseResult.buildSuccessResult("保存会议成功");
	}

	/**
	 * 会议参会详细
	 */
	@ApiOperation(value = "会议参会详细", notes = "查询会议用户参会详细信息列表数据")
	@RequestMapping(value="/approvalNoticeInfoSetDetailsList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public ResponseResult getApprovalNoticeInfoSetDetailsList(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 当前页
			String currentPage = request.getParameter("page");
			// 一页显示条数
			String pageSize = request.getParameter("pageSize");
			Map<String, Object> map = new HashMap<String, Object>();
			String id = request.getParameter("id");
			String type = request.getParameter("type");
			List<Map> list = new ArrayList<>();
			// 查询会议参会详细
			if("0".equals(type) || "1".equals(type) || "2".equals(type)) {
				list = this.applyRecordDingService.getApplyRecordNoticeList(request, currentPage, pageSize, id, type,
						map);
			} else if ("3".equals(type) || "4".equals(type)) {
				list = this.applyRecordDingService.getApplyRecordSigned(request, currentPage, pageSize, id, type, map);
			}
			resultMap.put("data", list);
			resultMap.put("currentPage", Integer.parseInt(currentPage));
		} catch (Exception e) {
			resultMap.put("success", false);
			resultMap.put("content", "");
		}
		return ResponseResult.buildSuccessResult(resultMap);
	}
	
	/**
	 * 会议参会详细
	 */
	@ApiOperation(value = "会议参会详细", notes = "查询会议用户参会详细信息列表数据")
	@RequestMapping(value="/getAllApprovalUserIds", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
	@ResponseBody
	public ResponseResult getAllApprovalUserIds(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			WebUser user = WebUtils.getCurrentUser();
			String token = user.getJwtToken();
			String id = request.getParameter("id");
			String type = request.getParameter("type");
			
			List<Map> list = new ArrayList<>();
			List<String> data = new ArrayList<>();
			String userIds = "";
			if("end".equals(type)){
				List<Object[]> userList = this.signedInfoService.getSignedUserList(id, 0);
				List<Map<String, Object>> users = new ArrayList<>();
				for(int i=0;i<userList.size();i++){
					Object[] objs = userList.get(i);
					Map<String, Object> map2 = new HashMap<>();
					map2.put("value", objs[0]);
					map2.put("text", objs[1]);
					map2.put("checked", false);
					map2.put("disable", false);
					users.add(map2);
				}
				map.put("userList", users);
			}else{
				// 查询会议参会详细
				if ("0".equals(type)) {
					list = this.applyRecordDingService.getApplyRecordNoticeList(request, "", "-2", id, type,
							map);
					for (Map<String, Object> map2 : list) {
						String userId = StringUtils.null2String(map2.get("userId"));
						if(StringUtils.isNotEmpty(userId)){
							userIds += userId + ",";
						}
					}
				} else if ("3".equals(type)) {
					list = this.applyRecordDingService.getApplyRecordSigned(request, "", "-2", id, type, map);
					for (Map<String, Object> map2 : list) {
						String signedUserId = StringUtils.null2String(map2.get("signedUserId"));
						if(StringUtils.isNotEmpty(signedUserId)){
							userIds += signedUserId + ",";
						}
					}
				}
				if(StringUtils.isNotEmpty(userIds) && userIds.charAt(userIds.length()-1) == ',') {
					userIds = userIds.substring(0, userIds.length() - 1);
				}
				//data = this.userApiService.getUserIdBySysOrThird(userIds, "1", "DD", corpId, token);
				map.put("data", userIds);
			}
		} catch (Exception e) {
			map.put("success", false);
			map.put("content", "");
		}
		return ResponseResult.buildSuccessResult(map);
	}
	
	/**
	 * 修改会议状态
	 */
	@ApiOperation(value = "修改会议状态", notes = "同意、驳回、取消会议申请")
    @RequestMapping(value = "/editApplyRecordInfo", method = RequestMethod.POST)
	@ResponseBody
    public ResponseResult editApplyRecordInfo(HttpServletRequest request) {
        WebUser wuser = WebUtils.getCurrentUser();
        String token = wuser.getJwtToken();
        try {
            String id =  request.getParameter("id");
            String nStatus = request.getParameter("status");
            //String noticeInfoId =  request.getParameter("noticeInfoId");
            String reason =  request.getParameter("reason");
            String messagePush=ValidateUtils.filter(request.getParameter("messagePushCheck"));
			String remindContent=ValidateUtils.filter(request.getParameter("remindContent"));
            String corpId = wuser.getCorpId();
            ApplyRecord applyRecord = this.applyRecordDingService.findOne(id);
            int status = applyRecord.getStatus();
            if(status!=0 && ("1".equals(nStatus)||"2".equals(nStatus))){
            	return ResponseResult.buildFailureResult("该会议已审批");
            }
            if(status == 3){
            	return ResponseResult.buildFailureResult("该会议已取消");
            }
            if("3".equals(nStatus) && status==1){
                List<String> taskIds = meetingTaskInfoService.findTaskInfoIdsByApplyRecordIds(id);
                //取消会议前删除会议相关任务
                this.meetingTaskInfoService.deleteByRecordId(id);
        		//删除相关会议消息
            	this.meetingSendMsgUtils.deleteMessage(taskIds, corpId, token);
            	//释放会议室
//            	if(StringUtils.isNotBlank(applyRecord.getBoardroomId())) {
//            		this.applyRecordService.saveNewBoardRoomApply(applyRecord);
//            	}
            }
            this.applyRecordDingService.editApplyRecordInfo(id,nStatus,reason,"changeStatus",token);
            BoardroomSet room = null;
            if(StringUtils.isNotBlank(applyRecord.getBoardroomId())) {
            	room = this.boardroomSetService.findOne(applyRecord.getBoardroomId());
            }
            //String isApprove = StringUtils.null2String(room.getIsApprove());
            if(("1".equals(nStatus)&& status==0) || "3".equals(nStatus) ){
            	Map<String, Object> ds = new HashMap<>();
            	if("1".equals(nStatus)){
            		ds.put("type", "2");
            	}else{
            		ds.put("type", "3");
            	}
            	ds.put("reason", reason);
    			ds.put("applyRecordId", applyRecord.getId());
    			ds.put("meetingTitle", applyRecord.getName());
    			ds.put("startTime", applyRecord.getStartTime());
    			ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(applyRecord.getAddress()) ? applyRecord.getAddress():"无") : room.getAddress());
    			String noticeUserId = applyRecord.getCreatedBy();
    			ds.put("userId", noticeUserId);
    			Map<String, Object> user =  this.userApiService.getUser(noticeUserId, corpId, "", token);
    			String userName = StringUtils.null2String(user.get("userName"));
    			ds.put("userName", userName);
    			ds.put("userOrg", applyRecord.getCreatedOrg());
    			List<String> userIdList = this.applyRecordService.getApplyRecordUserList(applyRecord, token);
    			if(CollectionUtils.isNotEmpty(userIdList)){
    				StringBuffer ids = new StringBuffer();
    				StringBuffer jsonIds = new StringBuffer("[");
    				for(int i = 0; i < userIdList.size(); i++) {
    					if(i == userIdList.size() - 1) {
    						ids.append(userIdList.get(i));
    						jsonIds.append("{\"10\":\"" + userIdList.get(i) + "\"}]");
    					}else {
    						ids.append(userIdList.get(i) + ",");
    						jsonIds.append("{\"10\":\"" + userIdList.get(i) + "\"},");
    					}
    				}
    				jsonIds.append("]");
	    			if(!StringUtils.isEmpty(ids.toString())){
	    				boolean mobilePush = false;
	    	            boolean emailPush = false;
	    	            boolean smsPublish = false;
	    				String mesgPush = messagePush;//applyRecord.getMessagePush();
	    				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
//	    				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
	    				emailPush = true;
	    				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
	    				ds.put("userIds", ids);
	    				ds.put("orgIds", "");
	    				ds.put("customMessage", remindContent);
	    				this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
	    				this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, token, request);
						this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, token);
	    			}
					if(!"[]".equals(jsonIds.toString())){
						this.meetingSendMsgUtils.sendMessage(ds, jsonIds.toString(), corpId, token);
					}
    			}
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.buildFailureResult("保存会议状态状态失败");
        }
        return ResponseResult.buildSuccessResult("保存会议状态状态成功");
    }
	
	/**
     * 删除会议
     */
    @ApiOperation(value = "删除会议", notes = "删除会议申请")
    @RequestMapping(value = "/deletApplyRecordInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult deletApplyRecordInfo(HttpServletRequest request) {
        try {
            String id =  request.getParameter("id");
            WebUser user = WebUtils.getCurrentUser();
            String token = user.getJwtToken();
            String corpId = user.getCorpId(); 
            List<String> dataIds = new ArrayList<String>();
            //删除关联的scope
        	List<String> attendUser = new ArrayList<>();
        	List<String> emceeUser = new ArrayList<>();
        	List<String> memoUser = new ArrayList<>();
        	ApplyRecord record = this.applyRecordDingService.findOne(id);
        	if(record == null) return ResponseResult.buildSuccessResult("删除会议成功");
        	dataIds.add(id);
    		List<String> taskIds = meetingTaskInfoService.findTaskInfoIdsByApplyRecordIds(id);
    		if(CollectionUtils.isNotEmpty(taskIds)) dataIds.addAll(taskIds);
			attendUser.add(record.getAttendUser());
			emceeUser.add(record.getEmceeUser());
			memoUser.add(record.getMemoUser());
        	this.popUserScopeUtilService.delScopeMethod("oa_meeting_apply_record_scope", attendUser, "oa_meeting_apply_record", "attend_user");
        	this.popUserScopeUtilService.delScopeMethod("oa_meeting_apply_record_scope", emceeUser, "oa_meeting_apply_record", "emcee_user");
        	this.popUserScopeUtilService.delScopeMethod("oa_meeting_apply_record_scope", memoUser, "oa_meeting_apply_record", "memo_user");
        	
        	//删除相关签到信息
        	this.signedInfoService.deleteSignInfo(id);
        	//删除相关定位签到地址信息
        	this.signedAddressService.deleteSignAddress(id);
        	//删除相关通知
        	this.noticeInfoService.deleteByApplyrecord(id);
        	//删除相关会议纪要
        	this.memoInfoService.deleteMemoInfo(id);
        	//删除相关会议任务
            this.meetingTaskInfoService.deleteByRecordId(id);
            this.applyRecordDingService.deleteApplyRecord(id);
            //删除相关会议消息
        	this.meetingSendMsgUtils.deleteMessage(dataIds, corpId, token);
        } catch (Exception e) {
        	e.printStackTrace();
        	return ResponseResult.buildFailureResult("删除会议状失败");
        }
        return ResponseResult.buildSuccessResult("删除会议成功");
    }
    
    /**
     * 提前结束会议
     */
    @ApiOperation(value = "提前结束会议", notes = "")
    @RequestMapping(value = "/endApplyRecord", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult endApplyRecord(HttpServletRequest request) {
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	try {
    		String id =  request.getParameter("id");
    		ApplyRecord record = this.applyRecordDingService.findOne(id);
        	if(record != null){
        		record.setStatus(5);
        		String current = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm");
        		record.setEndTime(current);
        		this.applyRecordDingService.save(record);
        	}
    	} catch (Exception e) {
    		e.printStackTrace();
    		return ResponseResult.buildFailureResult("操作失败");
    	}
    	return ResponseResult.buildSuccessResult("操作成功");
    }
    
    /**
	 * 修改会议签到状态
	 */
	@ApiOperation(value = "修改会议签到状态", notes = "会议签到")
    @RequestMapping(value = "/editSignedInfo", method = RequestMethod.POST)
    public ResponseResult editSignedInfo(HttpServletRequest request) {
        try {
            String id = request.getParameter("id");
            this.signedInfoService.editSignedInfo(id);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.buildSuccessResult("保存会议签到状态失败");
        }
        return ResponseResult.buildSuccessResult("保存会议签到状态成功");
    }
	
	/**
     * 会议纪要
     */
    @ApiOperation(value="会议纪要", notes="查询会议纪要list列表数据")
    @RequestMapping(value="/memoInfoList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getMemoInfoList(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition");
            //0未读、1已读
            String type = request.getParameter("type");
            String userId = user.getUserId();
            String corpId = user.getCorpId();
            
            //查询会议纪要列表数据
            List<Map> list = this.memoInfoService.getMemoInfoList(currentPage, pageSize,userId,corpId,"0",condition,type);
            map.put("data", list);
            map.put("currentPage", Integer.parseInt(currentPage));
        }catch(Exception e){
            e.printStackTrace();
            map.put("success", false);
            map.put("content", "");
        }
        return ResponseResult.buildSuccessResult(map);
    }
    
    /**
     * 新建、编辑会议纪要
     * @param request
     * @return
     */
    @ApiOperation(value="会议纪要", notes="新建、编辑会议纪要")
    @RequestMapping(value="/editMemoInfo", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult editMemoInfo(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            String corpId = user.getCorpId();
            String userId = user.getUserId();
            String token = user.getJwtToken();
            String id = request.getParameter("id");
            String applyRecordId = request.getParameter("applyRecordId");
            String isViewType = request.getParameter("isViewType");
            String cnName = user.getCnName();
            String userName = user.getUserName();
            MemoInfo memoInfo = null;
            Object attIdJson = null;
            if(StringUtils.isNotEmpty(id)){
                memoInfo = this.memoInfoService.findOne(id);
                if(memoInfo==null){
                	map.put("isDeleted", true);
                	return ResponseResult.buildSuccessResult(map);
                }else{
                	map.put("isDeleted", false);
                    if(isViewType.equals("1")){
                        MemoUserInfo memoUserInfo = this.memoUserInfoService.getMemoUserInfo(id, userId, corpId);
                        if(memoUserInfo!=null){
                            //修改状态
                            memoUserInfo.setIsView(1);
                            this.memoUserInfoService.save(memoUserInfo);
                        }
                    }
                }
                attIdJson = memoInfoService.transformAttachmentPlanform2Dd(StringUtils.null2String(memoInfo.getFileId()), token);
            }else{
                memoInfo = new MemoInfo();
            }
            //查询会议
            map = this.applyRecordDingService.getMemoApplyRecordContent(applyRecordId,corpId,token);
            ApplyRecord applyRecord = (ApplyRecord)map.get("applyRecord");
            map.put("isCreatedBy", userId.equals(StringUtils.null2String(applyRecord.getCreatedBy())));
            //主持人
            boolean isEmceeUser = false;
			List<String> eScopeList = new ArrayList<>();
			eScopeList.add(applyRecord.getEmceeUser());
			List<MeetingScope> emceeUserScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "emcee_user", eScopeList,true);
			if(emceeUserScopeList!=null && emceeUserScopeList.size()>0){
				for(MeetingScope m : emceeUserScopeList){
					String scopeValue = m.getScopevalue();
					if(scopeValue.equals(userId)){
						isEmceeUser = true;
					}
				}
			}
			map.put("isEmceeUser", isEmceeUser);
			//纪要员
			boolean isMemoUser = false;
			List<String> mScopeList = new ArrayList<>();
			mScopeList.add(applyRecord.getMemoUser());
			List<MeetingScope> memoUserScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "memo_user", mScopeList,true);
			if(memoUserScopeList!=null && memoUserScopeList.size()>0){
				for(MeetingScope m : memoUserScopeList){
					String scopeValue = m.getScopevalue();
					if(scopeValue.equals(userId)){
						isMemoUser = true;
					}
				}
			}
            map.put("isMemoUser", isMemoUser);
            map.put("memoInfo", memoInfo);
            map.put("attIdJson", attIdJson);
            map.put("fileIds", StringUtils.null2String(memoInfo.getFileId()));
            String sysWatermark = commonService.getSysParamValueByMark(corpId, token, "sysWatermark");
            if(StringUtils.isNotBlank(sysWatermark) && sysWatermark.contains("meetingMemo")) {
            	map.put("watermarkContent", cnName + userName);
            	map.put("watermark", "1");
            }else {
            	map.put("watermark", "1");
            	map.put("watermarkContent", cnName + userName);
            }
        }catch(Exception e){
        	e.printStackTrace();
        	map.put("success", false);
        	map.put("content", "");
        }
        return ResponseResult.buildSuccessResult(map);
    }
    
    @ApiOperation(value = "保存会议纪要", notes = "保存会议纪要")
    @RequestMapping(value = "/saveMemoInfo", method = RequestMethod.POST)
    public ResponseResult saveMemoInfo(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String token = user.getJwtToken();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
        	String message = request.getParameter("message");
        	Map<String,String> paramsMap = new HashMap<String,String>();
//            paramsMap.put("message", message);
            paramsMap.put("token", token);
            paramsMap.put("userId", user.getUserId());
            paramsMap.put("userName", user.getCnName());
            paramsMap.put("corpId", user.getCorpId());
            paramsMap.put("org", user.getOrgId());
            RestClient restClient = new RestClient();
    		String configJson = restClient.post("/meeting/memoInfo/saveMemoInfo", token, paramsMap,message);
    		Map<String, Object> result = JsonUtils.readValue(configJson);
    		String type = StringUtils.null2String(result.get("type"));
    		if("success".equals(type)){
    			resultMap.put("success", Boolean.valueOf(true));
                resultMap.put("content", "保存会议纪要成功");
            }else{
            	resultMap.put("success", Boolean.valueOf(false));
                resultMap.put("errorMsg", "保存会议纪要失败");
            }
        } catch (Exception e) {
            resultMap.put("success", Boolean.valueOf(false));
            resultMap.put("errorMsg", "保存会议纪要失败");
            e.printStackTrace();
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    @ApiOperation(value = "变更记录人", notes = "变更记录人")
    @RequestMapping(value = "/changMemoUser", method = RequestMethod.POST)
    public ResponseResult changMemoUser(HttpServletRequest request) {
        try {
        	String applyRecordId = ValidateUtils.filter(request.getParameter("applyRecordId"));
    		String memoUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrMemoUser"));
    		if(StringUtils.isNotBlank(memoUserJsonStr)) {
				Map<String, String> map = noticeInfoService.getUserIdAndName(memoUserJsonStr);
				String newMemoUserId = map.get("id");
				String newMemoUserName = map.get("name");
				searchService.changMemoUser(applyRecordId, newMemoUserId, newMemoUserName);
    		}
        } catch (Exception e) {
            ResponseResult.buildFailureResult("变更失败");
            e.printStackTrace();
        }
        return ResponseResult.buildSuccessResult("变更成功");
    }
	
    /**
     * 会议室
     */
    @ApiOperation(value="会议室", notes="查询会议室list列表数据")
    @RequestMapping(value = "/boardroomSetList", method = RequestMethod.GET,produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getBoardroomSetList(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //查询条件
            String condition = request.getParameter("condition");
            String boardroomName = request.getParameter("boardroomName");
            String corpId = "";
            if(user == null){
            	corpId = "0";
            }else{
            	corpId = user.getCorpId();
            }
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            //查询会议通知列表数据
            if(StringUtils.isNotBlank(boardroomName)) {
            	list = this.boardroomSetService.getBoardroomList(boardroomName,corpId,condition);
            }else {
            	list = this.boardroomSetService.getBoardroomList(corpId,condition);
            }
            resultMap.put("data", list);
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    /**
     * 会议室
     */
    @ApiOperation(value="会议室", notes="查询会议室详情")
    @RequestMapping(value = "/boardRoomInfo", method = RequestMethod.GET,produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult boardRoomInfo(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //查询条件
            String id = request.getParameter("id");
            String date = request.getParameter("date");
            String token = user.getJwtToken();
            String corpId = "";
            if(user == null){
            	corpId = "0";
            }else{
            	corpId = user.getCorpId();
            }
            BoardroomSet boardroomSet = this.boardroomSetService.findOne(id);
			String adminUser = boardroomSet.getAdminUserScope();
			String scopeTypeStr = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_boardroom_set", "admin_user_scope", StringUtils.null2String(adminUser));
            //管理员
            map.put("adminUsers", "");
            if(StringUtils.isNotEmpty(scopeTypeStr)) {
                String scopeName = this.userApiService.getScopeName(scopeTypeStr, corpId, token);
                map.put("adminUsers", scopeName);
            }
	        BoardroomCategorySet bcs = this.boardroomCategorySetService.findOne(boardroomSet.getCategoryId());
	        String categoryName = "";
	        if(bcs!=null){
	            categoryName = bcs.getName();
	        }
	        map.put("categoryName", categoryName);
            List<Map> server = this.serveSetService.getServeSetList(request, corpId);
            map.put("boardroomSet", boardroomSet);
            String limitDate = this.boardroomSetService.getLimitDate(boardroomSet.getBeforeDays());
            map.put("limitDate", limitDate);
            String times = this.applyRecordDingService.getApplyRecordByRoomId(id, date, corpId);
            map.put("times", times);
            map.put("server", server);
        }catch(Exception e){
        	e.printStackTrace();
        	map.put("success", false);
        	map.put("content", "");
        }
        return ResponseResult.buildSuccessResult(map);
    }
    
    @ApiOperation(value="获取入会（全时）参数", notes="获取入会（全时）参数")
    @RequestMapping(value = "/getJoinQsMeetingInfo", method = RequestMethod.GET,produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getJoinQsMeetingInfo(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        try{
            //WebUser user = WebUtils.getCurrentUser();
            //查询条件
            String curUserId = request.getParameter("curUserId");
            String applyRecordId = request.getParameter("applyRecordId");
            //String token = user.getJwtToken();
            Map qsmap = this.serveSetService.getQsMeetingInfoById(applyRecordId);
            //主持人
            if((qsmap.get("emceeUser")+"").equals(curUserId)) {
            	map.put("meetingCode", qsmap.get("pcode1")+"");
            }else {
            	map.put("meetingCode", qsmap.get("pcode2")+"");
            }
            map.put("meetingId", qsmap.get("conferenceId")+"");
            
            Map qsusermap = this.serveSetService.getQsUserInfoById(curUserId);
            map.put("username", qsusermap.get("qsuserName")+"");
            map.put("userId", qsusermap.get("qsemail")+"");
            map.put("success", "0");
        }catch(Exception e){
        	e.printStackTrace();
        	map.put("success", "-1");
        }
        return ResponseResult.buildSuccessResult(map);
    }
    
    @ApiOperation(value="判断会议室是否被占用", notes="判断会议室是否被占用")
    @RequestMapping(value = "/boardRoomIsExist", method = RequestMethod.GET,produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult boardRoomIsExist(HttpServletRequest request) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	LOGGER.info("--boardRoomIsExist--");
    	String SDate = request.getParameter("SDate");
    	String EDate = request.getParameter("EDate");
    	String boardRoomId = request.getParameter("boardRoomId");
    	String applyRecordId = request.getParameter("applyRecordId");
    	LOGGER.info("--SDate:"+SDate);
    	LOGGER.info("--EDate:"+EDate);
    	LOGGER.info("--boardRoomId:"+boardRoomId);
		List<ApplyRecord> list = this.applyRecordService.getApplyRecordByApp(SDate,EDate,boardRoomId,applyRecordId);
		if(list == null||list.size()==0) {
			map.put("exist", 1);
		}else {
			map.put("exist", 0);
		}
        return ResponseResult.buildSuccessResult(map);
    }
    
    /**
     * 扫码或定位签到
     */
    @ApiOperation(value="扫码或定位签到", notes="签到")
    @RequestMapping(value = "/userSigned", method = RequestMethod.GET,produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult userSigned(HttpServletRequest request) {
    	
    	LOGGER.debug("-----userSigned----");
    	
    	Map<String,Object> map = new HashMap<String,Object>();
    	try{
    		WebUser user = WebUtils.getCurrentUser();
    		String userId = user.getUserId();
    		LOGGER.debug("-userId:"+userId);
    		//查询条件
    		String id = request.getParameter("id");
    		LOGGER.debug("-id:"+id);
    		String signType = request.getParameter("signType");
    		String signedAddress = request.getParameter("signedAddress");
    		String token = user.getJwtToken();
    		LOGGER.debug("-token:"+token);
    		SignedInfo signedInfo = this.signedInfoService.getSignedInfo(userId, id);
            NoticeInfo noticeInfo = this.noticeInfoService.findAttendByApplyrecordId(id, userId, "1");
            if(noticeInfo==null || signedInfo == null){//没有参加会议
            	map.put("status", "-1");
            }else{
            	ApplyRecord record = this.applyRecordDingService.findOne(id);
                String signedTime = StringUtils.null2String(record.getSignedTime());
                int flag = 0;
                LOGGER.debug("-signedTime:"+signedTime);
                if(!"0".equals(signedTime)){
                	String startTime = record.getStartTime() + ":00";
                    Date start = DateUtils.parseTime(startTime);
                    Date signTime = DateUtils.addMinutes(start, -Integer.parseInt(signedTime));
                    flag = DateUtils.truncatedCompareTo(signTime, new Date(), Calendar.MILLISECOND);
                }
                String status = StringUtils.null2String(record.getStatus());
                LOGGER.debug("-status:"+status);
                if("1".equals(status) || "4".equals(status)){
                	if(flag < 1){
                		String signedType = record.getSignedType();
//                		String currentDate = DateUtils.formatTimeNow();
                		Date currentDate = new Date();
                		if("0".equals(signType)){//扫码签到
                			String isSigned = "s";
                    		if("2".equals(signedType)){
                    			String signed = StringUtils.null2String(signedInfo.getIsSigned());
                    			if(signed.indexOf("d") >= 0){//已定位签到
                    				isSigned = "sd";
                    			}
                    		}
                    		signedInfo.setIsSigned(isSigned);
                    		signedInfo.setQrcodeTime(currentDate);
                		}else{//定位签到
                			String isSigned = "d";
                    		if("2".equals(signedType)){
                    			String signed = StringUtils.null2String(signedInfo.getIsSigned());
                    			if(signed.indexOf("s") >= 0){//已扫码签到
                    				isSigned = "sd";
                    			}
                    		}
                    		signedInfo.setIsSigned(isSigned);
                    		signedInfo.setPositionTime(currentDate);
                    		signedInfo.setSignedAddress(signedAddress);
                		}
                    	this.signedInfoService.save(signedInfo);
                    	map.put("status", "0");//签到成功
                    	map.put("isSigned", signedInfo.getIsSigned());//签到成功
                    	map.put("positionTime", currentDate);//签到成功
                    }else{
                    	map.put("status", "1");//没有到签到时间
                    }
                }else if("5".equals(status)){
                	map.put("status", "2");//会议已结束
                }else if("3".equals(status)){
                	map.put("status", "3");//会议已取消
                }
            }
    	}catch(Exception e){
    		e.printStackTrace();
    		map.put("success", false);
    		map.put("content", "");
    	}
    	return ResponseResult.buildSuccessResult(map);
    }
    
    /**
     * 会议室
     */
    @ApiOperation(value="会议室", notes="查询会议室管理员")
    @RequestMapping(value = "/getBoardroomAdmin", method = RequestMethod.GET,produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getBoardroomAdmin(HttpServletRequest request) {
    	Map<String,Object> map = new HashMap<String,Object>();
    	try{
    		WebUser user = WebUtils.getCurrentUser();
    		//查询条件
    		String id = request.getParameter("id");
    		String corpId = "";
    		if(user == null){
    			corpId = "0";
    		}else{
    			corpId = user.getCorpId();
    		}
    		String token = user.getJwtToken();
    		
    		//查询会议通知列表数据
    		BoardroomSet room = this.boardroomSetService.findOne(id);
    		String scopeId = room.getAdminUserScope();
            List<String> idList = this.popUserScopeUtilService.getScopeValue("oa_meeting_apply_record_scope", "oa_meeting_boardroom_set", "admin_user_scope", scopeId);
            String ids = "";
            if(idList!=null && idList.size()>0){
            	for(int i=0; i<idList.size(); i++){
                	ids += idList.get(i) + ",";
                }
                if(ids.length()>0){
                	ids = ids.substring(0, ids.length()-1);
                }
                List<String> uuIds = this.userApiService.getUserIdBySysOrThird(ids, "1", "DD", corpId, token);
                map.put("userId", uuIds);
            }
    	}catch(Exception e){
    		e.printStackTrace();
    		map.put("success", false);
    		map.put("content", "");
    	}
    	return ResponseResult.buildSuccessResult(map);
    }
    
    /**
     * 查询会议室的服务树数据
     * 
     * @return
     */
    @RequestMapping(value = "/getBoardRoomServeTreeData", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult getBoardRoomServeTreeData(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        Map<String,Object> resultMap = new HashMap<String,Object>();
        String corpId = "";
        if(user == null){
        	corpId = "0";
        }else{
        	corpId = user.getCorpId();
        }
        String boardroomId = request.getParameter("boardroomId");
        
        List jeson = this.serveSetService.getBoardRoomServeTreeDataList(corpId,boardroomId);
        resultMap.put("serve", jeson);
        BoardroomSet boardroom = this.boardroomSetService.findOne(boardroomId);
        resultMap.put("boardRoom", boardroom);
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    @ApiOperation(value="查询我收到的会通知", notes="查询我收到的会通知")
    @RequestMapping(value="/receivedNoticeList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    public ResponseResult getReceivedNoticeList(HttpServletRequest request) {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition"); 
            String userId = user.getUserId();
            String corpId = user.getCorpId();
            List<Map> list = noticeInfoService.getNoticeListDing(currentPage, pageSize, userId, corpId, condition);
            resultMap.put("data", list);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
            
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    @ApiOperation(value="查询我发起的会议列表", notes="查询我发起的会议列表")
    @RequestMapping(value="/sendNoticeList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    public ResponseResult findNoticeInfoListByMe(HttpServletRequest request) {
    	LOGGER.debug("-----findNoticeInfoListByMe----");
        Map<String,Object> resultMap = new HashMap<String,Object>();
        try{
            WebUser user = WebUtils.getCurrentUser();
            //当前页
            String currentPage = request.getParameter("page");
            //一页显示条数
            String pageSize = request.getParameter("pageSize");
            //查询条件
            String condition = request.getParameter("condition"); 
            LOGGER.debug("---currentPage:"+currentPage);
            LOGGER.debug("---pageSize:"+pageSize);
            LOGGER.debug("---condition:"+condition);
            
            String userId = user.getUserId();
            String corpId = user.getCorpId();
            List<Map> list = noticeInfoService.findNoticeInfoListByMeDing(currentPage, pageSize, userId, corpId, condition);
            resultMap.put("data", list);
            resultMap.put("currentPage", Integer.parseInt(currentPage));
            
        }catch(Exception e){
        	e.printStackTrace();
        	resultMap.put("success", false);
        	resultMap.put("content", "");
        }
        return ResponseResult.buildSuccessResult(resultMap);
    }
    
    /**
     * 获取二维码
     * 
     * @return
     */
    @RequestMapping(value = "/getQrcodeAttachment", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult getQrcodeAttachment(HttpServletRequest request) {
    	Map<String,Object> resultMap = new HashMap<String,Object>();
    	String id = StringUtils.null2String(request.getParameter("id"));
    	String corpId = StringUtils.null2String(request.getParameter("corpId"));
    	String token = StringUtils.null2String(request.getParameter("token"));
//    	String url = GlobalConstant.getFlexOfficePageUrl(request);
//		if(StringUtils.isEmpty(url)) url = GlobalConstant.getFlexOfficeQrcodeUrl(request);
    	
    	GlobalConstant globalConstant = new GlobalConstant();// 读取配置文件class
    	String qrcodeUrl = globalConstant.getConfig("app.flexoffice.qrcode.url");
    	
    	
    	ApplyRecord record = this.applyRecordDingService.findOne(id);
		String attachId = record.getQrcodeAttach();
//        Urlconvert urlconvert = new Urlconvert();
//        urlconvert.setDingUrl(this.getMessageUrl("0", id, corpId, token));
//        urlconvert.setWxUrl(this.getMessageUrl("1", id, corpId, token));
//        urlconvert.setMhUrl(this.getMessageUrl("2", id, corpId, token));
//        urlconvert = this.urlconvertService.save(urlconvert);
//        String qrUrl = "/mobile/modules/meeting/dist/index.html?dd_nav_bgcolor=FF5E97F6#/meeting/qrCodeRedirect/"+urlconvert.getId();
        String qrUrl = "/mobile/modules/meeting/dist/index.html?context="+qrcodeUrl+"&dd_nav_bgcolor=FF5E97F6#/meeting/qrcodeSign/" + id;
        attachId = this.createQrCode(request, qrUrl, token);
        record.setQrcodeAttach(attachId);
        this.applyRecordDingService.save(record);
        resultMap.put("attachments", attachId);
    	return ResponseResult.buildSuccessResult(resultMap);
    }
    
    /**
	 * 获取各个平台签到路径
	 * @param type 0:钉钉 1:企业微信 2:移动平台
	 * @param id
	 * @param webUrl
	 * @param corpId
	 * @param token
	 * @return
	 */
	private String getMessageUrl(String type, String id, String corpId, String token) {
		String messageUrl = "";
		String appId = "";
		String corpReally = "";
		if("2".equals(type)) {
			messageUrl = "/mobile/modules/meeting/dist/index.html?dd_nav_bgcolor=FF5E97F6#/meeting/qrcodeSign/" + id;
		}else {
			Map<String,Object> mpMap = mobileParamdataService.getParamDataMap(corpId, "meeting", type, token);
	    	if(MapUtils.isNotEmpty(mpMap)) {
	    		String code = String.valueOf(mpMap.get("code"));
	    		if(code.equals("0")) {//获取成功
	    			corpReally = String.valueOf(mpMap.get("corpId"));
	    			appId = String.valueOf(mpMap.get("agentId"));
	    		}
	    	}
			messageUrl = "/mobile/modules/meeting/dist/index.html"
	                + "?appid=" + appId
	                + "&corpid=" + corpReally
	                + "&dd_nav_bgcolor=FF5E97F6#/meeting/qrcodeSign"
	                + "/" + id;
		}
		return messageUrl;
	}
	
	/**
     * 生成二维码图片
     *
     * @param content
     */
    public String createQrCode(HttpServletRequest request, String content, String token) {
    	String attId = "";
    	try {
    		//计算二维码图片的高宽比
            // API文档规定计算图片宽高的方式 ，v是本次测试的版本号
            int v = 9;
            int width = 67 + 12 * (v - 1);
            int height = 67 + 12 * (v - 1);
        	Qrcode qrcode = new Qrcode();  
            qrcode.setQrcodeErrorCorrect('M');//纠错等级（分为L、M、H三个等级）  
            qrcode.setQrcodeEncodeMode('B');//N代表数字，A代表a-Z，B代表其它字符  
            qrcode.setQrcodeVersion(v);//版本    
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
            //绘图  
            Graphics2D gs = bufferedImage.createGraphics();  
            gs.setBackground(Color.WHITE);  
            gs.setColor(Color.BLACK);  
            gs.clearRect(0, 0, width, height);//清除下画板内容  
              
            //设置下偏移量,如果不加偏移量，有时会导致出错。  
            int pixoff = 2; 
            //String qrData="www.baidu.com";
              
            byte[] d = content.getBytes("utf-8");
            if(d.length > 0){  
                boolean[][] s = qrcode.calQrcode(d);
                for(int i=0;i<s.length;i++){  
                    for(int j=0;j<s.length;j++){  
                        if(s[j][i]){  
                            gs.fillRect(j*3+pixoff, i*3+pixoff, 3, 3);  
                        }  
                    }  
                }  
            }  
            gs.dispose();  
            bufferedImage.flush();  

            // 生成二维码QRCode图片
            String pathTime=DateUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS");
		    String path = org.ezplatform.util.http.WebUtils.getWebRealPath(request)+"attachment\\meetingUpload\\"+pathTime+"\\" ;
			File file = new File(path);
			if(!file.exists()){//判断文件目录是否存在    
				file.mkdirs();  
            }  
			String filePath = path + "qrcode" + pathTime + ".png";
			file = new File(filePath);
            // 生成的图片在D盘下，名为 qrCode.png
			ImageIO.write(bufferedImage, "png", file);
			
			
			
            List<Map<String,Object>> list =(List<Map<String, Object>>) this.attachmentUtilsService.upload("meeting",file,token);
    		if(null!=list && list.size()>0){
    			list.get(0).get("id");
    			if(StringUtils.isNotBlank(attId)){
    				attId+="|"+list.get(0).get("id");
    			}else{
    				attId=(String) list.get(0).get("id");
    			}
    		}
    		file.delete();
    		File f = new File(path);
    		if(f.exists()){
    			f.delete();
    		}
        } catch (Exception e) {
            e.printStackTrace();
        }
    	return attId;
    }
    
    /**
	 * 会议任务
	 */
	@ApiOperation(value = "会议任务", notes = "查询会议任务列表数据")
	@RequestMapping(value="/findTaskList", method=RequestMethod.GET, produces={"application/json; charset=UTF-8"})
    @ResponseBody
	public ResponseResult findTaskList(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			WebUser user = WebUtils.getCurrentUser();
			String corpId = user.getCorpId();
			String userId = user.getUserId();
			// 当前页
			String currentPage = request.getParameter("page");
			// 一页显示条数
			String pageSize = request.getParameter("pageSize");
			String status = request.getParameter("status");
			String applyrecordId = request.getParameter("applyRecordId");
			String title = request.getParameter("title");
			List<Map> list = this.meetingTaskInfoService.findTaskInfoByPage(status, currentPage, pageSize, applyrecordId, userId, corpId, title);
			resultMap.put("data", list);
			resultMap.put("currentPage", Integer.parseInt(currentPage));
		} catch (Exception e) {
			resultMap.put("success", false);
			resultMap.put("content", "");
		}
		return ResponseResult.buildSuccessResult(resultMap);
	}
	
	/**
     * 获取已超期和进行中任务数量
     * 
     * @return
     */
    @RequestMapping(value = "/taskInfosCount", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult taskInfosCount(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
		try {
			WebUser user = WebUtils.getCurrentUser();
			String token = user.getJwtToken();
			String corpId = user.getCorpId();
			String userId = user.getUserId();
			String applyrecordId = request.getParameter("applyrecordId");
			String title = request.getParameter("title");
			//已超期任务
            int expiredCount = this.meetingTaskInfoService.taskInfosCount("0", applyrecordId, userId, corpId, title);
            //进行中任务
            int inProgressCount = this.meetingTaskInfoService.taskInfosCount("1", applyrecordId, userId, corpId, title);
            //已完成任务
            int completeCount = this.meetingTaskInfoService.taskInfosCount("2", applyrecordId, userId, corpId, title);
            
            map.put("expiredCount", expiredCount);
            map.put("inProgressCount", inProgressCount);
            map.put("completeCount", completeCount);
            
            //判断是否是会议申请人和主持人
            if(!"".equals(applyrecordId)){
            	ApplyRecord record = this.applyRecordDingService.findOne(applyrecordId);
                String createdBy = record.getCreatedBy();
                List<String> eScopeList = new ArrayList<>();
                eScopeList.add(record.getEmceeUser());
                List<MeetingScope> emceeUserScopeList = this.meetingScopeService.getMeetingScopeList("oa_meeting_apply_record", "emcee_user", eScopeList,true);
                String emceeUser = "";
                if(emceeUserScopeList!=null && emceeUserScopeList.size()>0){
                	for(MeetingScope m : emceeUserScopeList){
                		emceeUser += m.getScopevalue()+",";
                	}
                }
                String isCreatedOrEmcee = "1";
                if(userId.equals(createdBy) || emceeUser.indexOf(userId)>=0){
                	isCreatedOrEmcee = "0";
                }
                map.put("isCreatedOrEmcee", isCreatedOrEmcee);
            }
		} catch (Exception e) {
			map.put("success", false);
			map.put("content", "");
		}
    	return ResponseResult.buildSuccessResult(map);
    }
    
    /**
     * 获取已超期和进行中任务数量
     * 
     * @return
     */
    /*@RequestMapping(value = "/taskEICount", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult taskEICount(HttpServletRequest request) {
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	try {
    		WebUser user = WebUtils.getCurrentUser();
    		String token = user.getJwtToken();
    		String corpId = user.getCorpId();
    		String userId = user.getUserId();
    		Map<String, Object> map = new HashMap<String, Object>();
    		
    		Map<String,String> paramsMap = new HashMap<String,String>();
    		paramsMap.put("corpId", corpId);
    		paramsMap.put("userId", userId);
    		
    		RestClient restClient = new RestClient();
    		String configJson = restClient.get("/meeting/taskInfo/taskEICount", token, paramsMap);
    		Map<String, Object> result = JsonUtils.readValue(configJson);
    		map = (Map<String, Object>) result.get("data");
    		map.put("userName", user.getCnName());
    		
    		resultMap.put("success", true);
    		resultMap.put("content", map);
    	} catch (Exception e) {
    		resultMap.put("success", false);
    		resultMap.put("content", "");
    	}
    	return ResponseResult.buildSuccessResult(resultMap);
    }*/
    
    /**
     * 获取任务详情
     * 
     * @return
     */
    @RequestMapping(value = "/getTaskInfo", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult getTaskInfo(HttpServletRequest request) {
    	LOGGER.debug("-----getTaskInfo----");
    	Map<String, Object> map = new HashMap<String, Object>();
		try {
			WebUser user = WebUtils.getCurrentUser();
			String token = user.getJwtToken();
			String corpId = user.getCorpId();
			String userId = user.getUserId();
			String taskInfoId = request.getParameter("taskInfoId");
			String recordId = request.getParameter("recordId");
			String editType = request.getParameter("editType");
			ApplyRecord record = null;
            if(!"".equals(recordId)){
            	record = this.applyRecordDingService.findOne(recordId);
            	if(record == null) {
                	map.put("isDeleted", true);
                	return ResponseResult.buildSuccessResult(map);
                }else {
                	map.put("isDeleted", false);
                }
                map.put("recordName", record.getName());
                
    			if(StringUtils.isNotEmpty(recordId)){
    				ApplyRecord applyRecord = this.applyRecordDingService.findOne(recordId);
    				if(applyRecord != null){
    					String emceeUser = applyRecord.getEmceeUser();
    					String memoUser = applyRecord.getMemoUser();
    					String attendUser = applyRecord.getAttendUser();
    					List<Map> maps = this.applyRecordDingService.getAllMeetingUsers(emceeUser, memoUser, attendUser);
    					map.put("limitDataUsers", maps);
    				}
    			}
            }
            if(StringUtils.isNoneBlank(taskInfoId)){
            	MeetingTaskInfo info = this.meetingTaskInfoService.findOne(taskInfoId);
            	if(info == null) {
                	map.put("isDeleted", true);
                	return ResponseResult.buildSuccessResult(map);
                }else {
                	map.put("isDeleted", false);
                }
            	map.put("taskInfo", info);

            	if("".equals(recordId)){
            		recordId = info.getApplyRecordId();
                	record = this.applyRecordDingService.findOne(recordId);
                    map.put("recordName", record.getName());
                }
            	
                Map<String, String> textParams = new HashMap<>();
                textParams.put("corpId", corpId);
                // 负责人
                String responseUserName = applyRecordService.getScopeName("oa_meeting_task_info", info.getResponseUser(), "response_user");
                map.put("responseUserName", responseUserName);
                if(!"view".equals(editType)) {
                	List<Map<String, Object>> resUserMap = this.transformUserScope2Dd(info.getResponseUser(), "oa_meeting_apply_record_scope", "oa_meeting_task_info", "response_user", corpId, token);
                	if(resUserMap != null){
                		map.put("responseUserData", resUserMap);
                	}
                }else{//查看页
                	List<Map> resUserMap2 = applyRecordService.getScopeValues("oa_meeting_task_info", info.getResponseUser(), "response_user");
                    map.put("responseUserData", resUserMap2);
                	//当前用户是否是负责人
                	map.put("isResponse", "1");
                	if(CollectionUtils.isNotEmpty(resUserMap2)) {
                		for(Map m : resUserMap2) {
                			if(userId.equals((String)m.get("value"))){
                        		map.put("isResponse", "0");
                        		break;
                        	}
                		}
                	}
                	//创建人
                	String createdUser = info.getCreatedBy();
                	String createdUserName = applyRecordService.getUserNameById(createdUser);
                	map.put("createdUserName", createdUserName);
                	
                	//是否是会议申请人和主持人
                	map.put("canEdit", "1");
                    if(userId.equals(record.getCreatedBy())){
                    	map.put("canEdit", "0");
                    }else{
                    	String emceeUser = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_apply_record", "emcee_user", StringUtils.null2String(record.getEmceeUser()));
                    	if(StringUtils.isNotEmpty(emceeUser)){
                    		String[] emuser = emceeUser.split("SCOPE");
                    		if(emuser.length>1 && userId.equals(emuser[1])){
                        		map.put("canEdit", "0");
                        	}
                    	}
                    }
                }
            }
            String noticeType = commonService.getSysParamValueByMark(corpId, token,"sysImType");
            map.put("noticeType", noticeType);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("success", false);
			map.put("content", "");
		}
    	return ResponseResult.buildSuccessResult(map);
    }
    
    /**
     * 根据scope所需的信息获取scope中的用户,
     * 并将用户信息封装成钉钉salt-ui组件可接受格式
     *
     * @param fieldDataValue
     * @param tableName
     * @param fieldDataTable
     * @param fieldData
     * @return
     */
    private List<Map<String, Object>> transformUserScope2Dd(String fieldDataValue, String tableName, String fieldDataTable, String fieldData, String corpId, String token){
        List<Map<String, Object>> re = new ArrayList<>();
        String scopeTypeStr = this.popUserScopeUtilService.getScopeTypeValue(tableName, fieldDataTable, fieldData, StringUtils.null2String(fieldDataValue));
        String[] scopeTypeArray = scopeTypeStr.split(",");
        if(scopeTypeArray != null && scopeTypeArray.length>0) {
        	String ids = "";
        	for (int i = 0; i < scopeTypeArray.length; i++) {
                String[] info = scopeTypeArray[i].split("SCOPE");
                if (info.length > 1){
                	ids += info[1] + ",";
                }
            }
            Map<String, Object> m = null;
            List<Map<String, Object>> userList= this.userApiService.getUserList(ids, corpId, "", token);
            if(CollectionUtils.isNotEmpty(userList)) {
            	for(Map<String, Object> userMap : userList) {
            		m = new HashMap<String, Object>(2);
                    m.put("text", userMap.get("userName"));
                    m.put("value", userMap.get("id"));
                    re.add(m);
            	}
            }
        }
        return re;
    }
    
    /**
     * 获取签到详细信息
     * 
     * @return
     */
    @RequestMapping(value = "/getSignedInfo", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult getSignedInfo(HttpServletRequest request) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	try {
    		WebUser user = WebUtils.getCurrentUser();
    		String token = user.getJwtToken();
    		String userId = user.getUserId();
    		String applyRecordId = request.getParameter("applyRecordId");
    		SignedInfo signedInfo = this.signedInfoService.getSignedInfo(userId, applyRecordId);
			map.put("singedInfo", signedInfo);
			ApplyRecord record = this.applyRecordDingService.findOne(applyRecordId);
			map.put("record", record);
			List<SignedAddress> list = this.signedAddressService.findByRecordId(applyRecordId);
			map.put("addressList", list);
    	} catch (Exception e) {
    		map.put("success", false);
    		map.put("content", "");
    	}
    	return ResponseResult.buildSuccessResult(map);
    }

    /**
     * 检验会议室是否已预约
     *
     * @return
     */
    @RequestMapping(value = "/validateMeetingTime", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult validateMeetingTime(HttpServletRequest request) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		WebUser user = WebUtils.getCurrentUser();
    		String corpId = user.getCorpId();
            String id = StringUtils.null2String(request.getParameter("id"));
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            String boardroomId = request.getParameter("boardroomId");
            String isCycle = request.getParameter("isCycle");
            String cycleType = request.getParameter("cycleType");
            String cycleValue = request.getParameter("cycleValue");
            String cycleEndTime = request.getParameter("cycleEndTime");
            result.put("type", "1");
            String msg = "";
    		//验证会议开始结束时间是否在会议室的范围内
			msg = this.boardroomSetService.checkTime(boardroomId,startTime, endTime,corpId);
			if (StringUtils.isNotEmpty(msg)) {
				result.put("type", "0");
				result.put("msg", msg);
				return ResponseResult.buildSuccessResult(result);
			}
//    		}
    		//验证会议室在会议开始结束时间范围内是否已有会议
    		msg = this.applyRecordDingService.checkApplyRecordDate(id,startTime, endTime,boardroomId, corpId);
    		if (StringUtils.isNotEmpty(msg)) {
    			result.put("type", "0");
    			result.put("msg", msg);
    			return ResponseResult.buildSuccessResult(result);
    		}
    		//检测该会议室再周期内是否被占用
            if("1".equals(isCycle)) {
            	ApplyRecord entity = new ApplyRecord();
                entity.setStartTime(startTime);
                entity.setEndTime(endTime);
                entity.setBoardroomId(boardroomId);
                entity.setIsCycle(Integer.parseInt(isCycle));
            	entity.setCycleType(Integer.parseInt(cycleType));
            	entity.setCycleValue(cycleValue);
            	entity.setCycleEndTime(cycleEndTime);
            	List<Map<String, String>> cyclelist = this.applyRecordService.getCycleDateList(entity);
            	msg = this.applyRecordService.checkCycleApplyRecordDate(entity, cyclelist, corpId);
            	if (StringUtils.isNotEmpty(msg)) {
            		result.put("type", "0");
        			result.put("msg", msg);
        			return ResponseResult.buildSuccessResult(result);
            	}
            }
    	} catch (Exception e) {
    		result.put("success", false);
    		result.put("content", "");
    	}
    	return ResponseResult.buildSuccessResult(result);
    }

    @ApiOperation(value = "保存会议申请信息", notes = "保存会议申请信息")
	@RequestMapping(value = "/saveTaskInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult saveTaskInfo(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
		String token = user.getJwtToken();
		String corpId = user.getCorpId();
		String userId = user.getUserId();
		String message =  request.getParameter("message");
		try {
			Map<String, Object> map = JsonUtils.readValue(message);
			
			MeetingTaskInfo meetingTaskInfo = null;
			String id =  StringUtils.null2String(map.get("id"));
			if (StringUtils.isNotEmpty(id)) {
				meetingTaskInfo = this.meetingTaskInfoService.findOne(id);
			}
			if (meetingTaskInfo == null) {
				meetingTaskInfo = new MeetingTaskInfo();
			}
			
			//任务标题是否重复
			String applyRecordId = StringUtils.null2String(map.get("applyRecordId"));
			String title = StringUtils.null2String(map.get("title"));
			MeetingTaskInfo taskInfo = this.meetingTaskInfoService.findTaskByTitle(applyRecordId, title);
			if(taskInfo != null){
				if(StringUtils.isEmpty(id) || !taskInfo.getId().equals(id)){
					return ResponseResult.buildFailureResult("同一会议下的任务标题不能重复");
				}
			}
			meetingTaskInfo.setTitle(title);
			
			if("".equals(StringUtils.null2String(meetingTaskInfo.getId()))){
				meetingTaskInfo.setCreatedBy(userId);
				meetingTaskInfo.setCorpId(corpId);
			}else{
				meetingTaskInfo.setLastModifiedBy(userId);
			}
			
			String comDetails = StringUtils.null2String(map.get("comDetails"));
			meetingTaskInfo.setComDetails(comDetails);
			
			//任务截止时间
            String endTime =  StringUtils.null2String(map.get("endTime"));
            meetingTaskInfo.setEndTime(DateUtils.parseDate(endTime));
            meetingTaskInfo.setContent(StringUtils.null2String(map.get("content")));
            meetingTaskInfo.setApplyRecordId(applyRecordId);
			
			// 负责人
			String responseUser = meetingTaskInfo.getResponseUser();
			if (StringUtils.isEmpty(responseUser)) {
				responseUser = UuidUtils.UUID();
			}
			meetingTaskInfo.setResponseUser(responseUser);
			String resUserId = StringUtils.null2String(map.get("responseUserData"));
			List<String> resUserList = new ArrayList<>();
			String[] userIds = resUserId.split(",");
			resUserList = Arrays.asList(userIds);
			this.meetingScopeService.saveCopeList(resUserList,null,"oa_meeting_task_info","response_user",responseUser,corpId,token);
			
			// 任务进度
			meetingTaskInfo.setProgress(Integer.valueOf(StringUtils.null2String(map.get("progress"))));
			// 任务提醒
			meetingTaskInfo.setRemindTime(Integer.valueOf(StringUtils.null2String(map.get("remindTime"))));
			// 提醒方式
			meetingTaskInfo.setRemindType(StringUtils.null2String(map.get("remindType")));
			meetingTaskInfo = this.meetingTaskInfoService.save(meetingTaskInfo);
			
			if(StringUtils.isEmpty(id)){
				Map<String, Object> ds = new HashMap<>();
				ApplyRecord applyRecord = this.applyRecordDingService.findOne(applyRecordId);
				ds.put("type", "6");
				ds.put("applyRecordId", applyRecordId);
				ds.put("meetingName", applyRecord.getName());
				Date date = DateUtils.parseDate(endTime);
				ds.put("endTime", DateUtils.formatDate(date, "yyyy年MM月dd日"));
				ds.put("title", meetingTaskInfo.getTitle());
				ds.put("id", meetingTaskInfo.getId());
				String noticeUserId = meetingTaskInfo.getCreatedBy();
				ds.put("userId", noticeUserId);
				String noticeUserName = "";
				if(StringUtils.isNoneEmpty(noticeUserId)) {
					Map<String, Object> userMap = userApiService.getUser(noticeUserId, corpId, "", TOKEN);
					if(MapUtils.isNotEmpty(userMap)) {
						noticeUserName = StringUtils.null2String(userMap.get("userName"));
					}
				}
				ds.put("userName", noticeUserName);
				ds.put("userOrg", meetingTaskInfo.getCreatedOrg());
				Map<String, String> idsMap = new HashMap<>();
				idsMap = this.transformUserScopePlatform2Dd(meetingTaskInfo.getResponseUser(), "oa_meeting_task_info", "response_user", corpId, token);
				String idString = idsMap.get("ids");
				String jsonIds = "[" + idsMap.get("jsonIds");
				if(!StringUtils.isEmpty(idString)){
					boolean mobilePush = false;
		            boolean emailPush = false;
		            boolean smsPublish = false;
					String mesgPush = applyRecord.getMessagePush();
					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
					if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
					idString = idString.substring(0, idString.length()-1);
					ds.put("userIds", idString);
					ds.put("orgIds", "");
					this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
					this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, token, request);
					this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, token);
				}
				if(StringUtils.isNotEmpty(jsonIds)){
					jsonIds = jsonIds.substring(0, jsonIds.length()-1);
					jsonIds += "]";
					this.meetingSendMsgUtils.sendMessage(ds, jsonIds, corpId, token);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseResult.buildFailureResult("保存失败");
		}
		return ResponseResult.buildSuccessResult("保存成功");
	}
    
    private Map<String, String> transformUserScopePlatform2Dd(String fieldDataValue, String table, String fieldData, String corpId, String token){
        String ids = "", jsonIds = "";
		Map<String, String> result = new HashMap<>();
        String scopeTypeStr = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", table, fieldData, StringUtils.null2String(fieldDataValue));
        String[] scopeTypeArray = scopeTypeStr.split(",");
        if(scopeTypeArray != null && scopeTypeArray.length>0) {
            for (int i = 0; i < scopeTypeArray.length; i++) {
                String[] info = scopeTypeArray[i].split("SCOPE");
                if (info.length > 1){
                    String id  = info[1];
					jsonIds +="{\"10\":\""+id+"\"},";
					ids += id + ",";
//                    List<String> l = this.userApiService.getUserIdBySysOrThird(id, "1", "DD", corpId, token);
//                    if(l!=null && l.size()>0){
//                    	ids += l.get(0) + ",";
//                    }
                }
            }
        }
		result.put("jsonIds", jsonIds);
		result.put("ids", ids);
		return result;
    }
    
    @ApiOperation(value = "修改任务进度", notes = "根据任务id修改任务进度")
    @RequestMapping(value = "/changeProgress", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult changeProgress(HttpServletRequest request) {
    	Map<String, Object> resultMap;
		try {
			WebUser user = WebUtils.getCurrentUser();
			String token = user.getJwtToken();
			resultMap = new HashMap<String, Object>();
			String progress = request.getParameter("progress");
			String comDetails = request.getParameter("comDetails");
			String saveType = request.getParameter("type");
			String taskInfoId = request.getParameter("taskInfoId");
			
			if("1".equals(saveType)){
				comDetails = StringUtils.null2String(comDetails);
				this.meetingTaskInfoService.updateDetails(comDetails, taskInfoId);
			}else{
				progress = StringUtils.null2String(progress);
				this.meetingTaskInfoService.updateProgress(Integer.parseInt(progress), taskInfoId);
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
			ResponseResult.buildSuccessResult("保存失败");
		}
    	return ResponseResult.buildSuccessResult("保存成功");
    }
    
    @ApiOperation(value = "删除任务", notes = "根据任务id删除任务")
    @RequestMapping(value = "/deleteTask", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult deleteTask(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String token = user.getJwtToken();
    	String corpId = user.getCorpId();
    	String id = StringUtils.null2String(request.getParameter("taskInfoId"));
    	try {
    		//删除相关任务消息
        	this.meetingSendMsgUtils.deleteMessage(Arrays.asList(id), corpId, token);
    		this.meetingTaskInfoService.deleteTask(id);
    	} catch (Exception e) {
    		e.printStackTrace();
    		return ResponseResult.buildSuccessResult("删除失败");
    	}
    	return ResponseResult.buildSuccessResult("删除成功");
    }
    
    @ApiOperation(value = "修改签到信息", notes = "根据会议id和用户修改签到信息")
    @RequestMapping(value = "/updateSignInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult updateSignInfo(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String token = user.getJwtToken();
    	String signedUserIds = request.getParameter("signedUserIds");
    	String recordId = request.getParameter("applyRecordId");
    	String[] userIds = signedUserIds.split(",");
    	for (String userId : userIds) {
    		SignedInfo signedInfo = this.signedInfoService.getSignedInfo(userId, recordId);
        	if(signedInfo == null){
        		signedInfo = new SignedInfo();
        	}
        	ApplyRecord record = this.applyRecordDingService.findOne(recordId);
    		if(record != null){
    			String signedType = record.getSignedType();
//    			String currentDate = DateUtils.formatTimeNow();
    			Date currentDate = new Date();
    			String signed = "";
    			if("0".equals(signedType)){//扫码签到
    				signed = "s";
    				signedInfo.setQrcodeTime(currentDate);
    			}else{
    				if("1".equals(signedType)){//定位签到
    					signed = "d";
    				}else if("2".equals(signedType)){//扫码+定位签到
    					signed = "sd";
    					signedInfo.setQrcodeTime(currentDate);
    				}else if(!"0".equals(signedType)&&
							!"1".equals(signedType)&&
							!"2".equals(signedType)){//现场签到
						signed = "xc";
						signedInfo.setQrcodeTime(currentDate);
					}
    				signedInfo.setPositionTime(currentDate);
    				List<SignedAddress> list = this.signedAddressService.findByRecordId(recordId);
    				if(list!=null && list.size()>0){
    					SignedAddress address = list.get(0);
    					signedInfo.setSignedAddress(address.getSignedAddress());
    				}
    			}
    			signedInfo.setIsSigned(signed);
    			this.signedInfoService.save(signedInfo);
    		}else{
    			ResponseResult.buildFailureResult("保存失败");
    		}
		}
    	return ResponseResult.buildSuccessResult("保存成功");
    }

    /**
     * 修改会议状态
     * @param request
     */
    @ApiOperation(value = "修改会议状态", notes = "释放或是占用会议室资源")
    @RequestMapping(value = "/changeByStatusBpm", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult changeByStatusBpm(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String token = user.getJwtToken();
    	String nStatus = request.getParameter("status");
    	String id = request.getParameter("applyRecordId");
    	try {
			if(StringUtils.isNotEmpty(id)){
				ApplyRecord entity = this.applyRecordDingService.findOne(id);
				int status = entity.getStatus();
				String type = StringUtils.null2String(request.getParameter("type"));
				int changeStatus = status;
				if("cancel".equals(type)){//流程结束后取消会议室预约，释放会议室资源
					if (status == 0) {
						changeStatus = -1;
					}else if(status == -1){
						return ResponseResult.buildFailureResult("已取消预约");
					}else{
						return ResponseResult.buildFailureResult("已发起会议，不可取消预约");
					}
				}else{
					if("1".equals(nStatus)){//正常结束
						changeStatus = 1;
					}else if("0".equals(nStatus)){//驳回到发起人
						changeStatus = 2;
					}else if("3".equals(nStatus) || "2".equals(nStatus)){//发起人撤销或非正常结束
						changeStatus = -1;
					}else if("4".equals(nStatus)){//表单提交
						changeStatus = 0;
					}else if("7".equals(nStatus)){//结束
						String startTime = entity.getStartTime();
						SimpleDateFormat sf  = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
						Date _startTime = sf.parse(startTime + ":00");
						Date now = new Date();
						if(_startTime.getTime() < now.getTime()) changeStatus = -1;
						else changeStatus = 1;
					}
				}
				List<String> ids = new ArrayList<>();
				ids.add(id);
				this.applyRecordDingService.changeStatusById(changeStatus, ids);
				if(changeStatus == 1){//会议流程正常结束，会议为未召开状态，发送推送消息
					String corpId = StringUtils.null2String(request.getParameter("corpId"));
					this.applyRecordDingService.editApplyRecordInfo(entity.getId(),"1","", "",token);
					BoardroomSet room = null;
					if(StringUtils.isNotEmpty(entity.getBoardroomId())) {
						room = this.boardroomSetService.findOne(entity.getBoardroomId());
					}
					// 新建编辑会议发送会议申请通知
					int nStauts = entity.getStatus();
					String userIds = "", orgIds = "", jsonIds = "[";
					Map<String, Object> ds = new HashMap<>();
					ds.put("applyRecordId", id);
					ds.put("meetingTitle", entity.getName());
					ds.put("startTime", entity.getStartTime());
					ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(entity.getAddress()) ? entity.getAddress():"无") : room.getAddress());
					String noticeUserId = entity.getCreatedBy();
					String userName = "";
					if(StringUtils.isNotEmpty(noticeUserId)){
						Map<String, Object> userInfo = this.userApiService.getUser(noticeUserId, corpId,  "", token);
						if(userInfo != null){
							userName = StringUtils.null2String(userInfo.get("userName"));
						}
					}
					ds.put("userId", noticeUserId);
					ds.put("userName", userName);
					ds.put("userOrg", entity.getCreatedOrg());
					if(nStauts == 1){
						ds.put("type", "2");
						List<String> userIdList = this.applyRecordService.getApplyRecordUserList(entity, token);
						if(CollectionUtils.isNotEmpty(userIdList)){
	        				StringBuffer idsBuffer = new StringBuffer();
	        				StringBuffer jsonIdsBuffer = new StringBuffer("[");
	        				for(int i = 0; i < userIdList.size(); i++) {
	        					if(i == userIdList.size() - 1) {
	        						idsBuffer.append(userIdList.get(i));
	        						jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"}]");
	        					}else {
	        						idsBuffer.append(userIdList.get(i) + ",");
	        						jsonIdsBuffer.append("{\"10\":\"" + userIdList.get(i) + "\"},");
	        					}
	        				}
	        				jsonIdsBuffer.append("]");
	        				userIds = idsBuffer.toString();
	        				jsonIds = jsonIdsBuffer.toString();
						}
					}
					
					if(!StringUtils.isEmpty(userIds)){
						boolean mobilePush = false;
			            boolean emailPush = false;
			            boolean smsPublish = false;
						String mesgPush = entity.getMessagePush();
						if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
						if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
						if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
						ds.put("userIds", userIds);
						ds.put("orgIds", orgIds);
						this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
						this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, token, request);
    					this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, token);
					}
					if(StringUtils.isNotEmpty(jsonIds)){
						this.meetingSendMsgUtils.sendMessage(ds, jsonIds, corpId, token);
					}
				}
			}
        } catch (Exception e) {
           e.printStackTrace();
			return  ResponseResult.buildFailureResult("保存会议状态状态失败");
        }
        return  ResponseResult.buildSuccessResult("保存会议状态状态成功");
    }

    /**
     * 是否可发起会议或取消预约
     * @param request
     */
    @ApiOperation(value = "是否可发起会议或取消预约", notes = "预约会议室流程结束后判断是否可发起会议或是否可取消预约会议室")
    @RequestMapping(value = "/canCancelMeeting", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult canCancelMeeting(HttpServletRequest request) {
        String id = request.getParameter("applyRecordId");
        String result = "0";//不可取消会议
		try {
			if (StringUtils.isNotEmpty(id)) {
				ApplyRecord applyRecord = this.applyRecordDingService.findOne(id);
				if(applyRecord != null){
					int status = applyRecord.getStatus();
					if (status == 1) {
						result = "1"; //可取消会议
					}
				}
			}
		} catch (Exception e) {
			return ResponseResult.buildFailureResult("获取失败");
		}
		return ResponseResult.buildSuccessResult(result);
    }

    /**
     * 获得流程列表
     *
     * @param entity
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/getProcessInfoList", method = RequestMethod.GET, produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getProcessInfoList(String entity, HttpServletRequest request) throws ParseException {
        String type = request.getParameter("type");
        String page = request.getParameter("page");
        String pageSize = request.getParameter("pageSize");
        String search = StringUtils.null2String(request.getParameter("search"));
        RestClient restClient = new RestClient(true);
        int pageSizeInt = 10;
        int start = 0;

        if (StringUtils.isNotBlank(pageSize)) {
            pageSizeInt = Integer.parseInt(pageSize);

        }
        if (StringUtils.isNotBlank(page)) {
            start = (Integer.parseInt(page) - 1) * pageSizeInt;
        }

        WebUser user = WebUtils.getCurrentUser();

        String token = user.getJwtToken();
        String userId = user.getUserId();
        String orgId = user.getOrgId();
        String corpId = user.getCorpId();

        Map<String, String> paramMap = new HashMap<String, String>();
        Map<String, Object> searchMap = new HashMap<String, Object>();
        searchMap.put("title", search);
        searchMap.put("startUserName", "");
        paramMap.put("searchData", JsonUtils.writeValueAsString(searchMap));
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (type.equals("1")) {//待办
            paramMap.put("code", "");
            paramMap.put("category", "");
            paramMap.put("userId", userId);
            paramMap.put("groupId", orgId);
            paramMap.put("corpId", corpId);
            paramMap.put("index", start + "");
            paramMap.put("limit", pageSizeInt + "");
            paramMap.put("module", "meeting");

            try {
                String scopeMap1 = restClient.get("/bpm/runtime/getUndoTaskList", token, paramMap);
                Map<String, Object> map1 = JsonUtils.readValue(scopeMap1);
                if (map1.get("type").toString().equals("success")) {
                    Map<String, Object> resultMap1 = (Map<String, Object>) map1.get("data");
                    dataMap.put("data", resultMap1.get("list"));
                    dataMap.put("count", resultMap1.get("count"));
                    dataMap.put("currentPage", Integer.parseInt(page));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (type.equals("2")) {//已办
            paramMap.put("code", "");
            paramMap.put("category", "");
            paramMap.put("userId", userId);
            paramMap.put("groupId", orgId);
            paramMap.put("corpId", corpId);
            paramMap.put("index", start + "");
            paramMap.put("limit", pageSizeInt + "");
            paramMap.put("module", "meeting");
            try {
                String scopeMap1 = restClient.get("/bpm/runtime/getDoneProcessList", token, paramMap);
                Map<String, Object> map1 = JsonUtils.readValue(scopeMap1);
                if (map1.get("type").toString().equals("success")) {
                    Map<String, Object> resultMap1 = (Map<String, Object>) map1.get("data");
                    dataMap.put("data", resultMap1.get("list"));
                    dataMap.put("count", resultMap1.get("count"));
                    dataMap.put("currentPage", Integer.parseInt(page));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (type.equals("3")) {//我的
            paramMap.put("code", "");
            paramMap.put("category", "");
            paramMap.put("userId", userId);
            paramMap.put("groupId", orgId);
            paramMap.put("corpId", corpId);
            paramMap.put("index", start + "");
            paramMap.put("limit", pageSizeInt + "");
            paramMap.put("module", "meeting");
            try {
                String scopeMap1 = restClient.get("/bpm/runtime/getMyProcessList", token, paramMap);
                Map<String, Object> map1 = JsonUtils.readValue(scopeMap1);
                if (map1.get("type").toString().equals("success")) {
                    Map<String, Object> resultMap1 = (Map<String, Object>) map1.get("data");
                    dataMap.put("data", resultMap1.get("list"));
                    dataMap.put("count", resultMap1.get("count"));
                    dataMap.put("currentPage", Integer.parseInt(page));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseResult.buildSuccessResult(dataMap);
    }

    /**
     * 获取预约会议室流程详情
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getMeetingRoomBpmInfo", method = RequestMethod.POST, produces = {"application/json; charset=UTF-8"})
    @ResponseBody
    public ResponseResult getMeetingRoomBpmInfo(HttpServletRequest request) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        RestClient restClient = new RestClient(true);
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String userId = user.getUserId();
        String token = user.getJwtToken();
        String title = request.getParameter("title");
        String formId = request.getParameter("formId");
        String dataId = request.getParameter("dataId");
        String taskId = request.getParameter("taskId");
        String processInstanceId = request.getParameter("processInstanceId");
        //String dealwithId = request.getParameter("dealwithId");
        String type = request.getParameter("type");
        String logCode = "";
        if (type.equals("0")) logCode = "meeting:pending:03";//待办
        else if(type.equals("1")) logCode = "meeting:unRead:03";//待阅
        else if(type.equals("2")) logCode = "meeting:done:03";//已办
        else if(type.equals("3")) logCode = "meeting:read:03";//已阅
        else if(type.equals("4")) logCode = "meeting:my:03";//我的
        else if(type.equals("5")) type = "0";
        //String startUserId = request.getParameter("startUserId");
        //String handleUserId = request.getParameter("handleUserId");
        String boardroomId = StringUtils.null2String(request.getParameter("boardroomId"));
        String startTime = StringUtils.null2String(request.getParameter("startTime"));
        String endTime = StringUtils.null2String(request.getParameter("endTime"));
        String cycleEndTime = StringUtils.null2String(request.getParameter("cycleEndTime"));
        //查找表单详情
        Map<String, String> paramMap1 = new HashMap<String, String>();
        paramMap1.put("formId", formId);
        paramMap1.put("dataId", dataId);
        paramMap1.put("formType", "4");

        String handleUserDingId = "";
        //获取当前办理用户第三方id
//		if(StringUtils.isNoneBlank(handleUserId)){
//			Map<String, Object> userMap = userApiService.getUserInfo(handleUserId, corpId, token);
//			handleUserDingId = userMap.get("thirdUId").toString();
//		}
        Map<String, Object> map2 = null;
        if(type.equals("2")) {//已办
        	Map<String, String> formkeyParam = new HashMap<String, String>();
            formkeyParam.put("corpId", corpId);
            formkeyParam.put("userId", userId);
            formkeyParam.put("taskId", taskId);
            String formkeyConfigJson = restClient.get("/bpm/runtime/getProcessInfo", token, formkeyParam);
            map2 = JsonUtils.readValue(formkeyConfigJson);
            if ("0".equals(map2.get("code"))) {
            	Map<String, Object> formkeyForm = (Map<String, Object>)map2.get("data");
            	formId = (String)formkeyForm.get("formKey");
            }
        }
        Map<String, String> textParams = new HashMap<String, String>();
        textParams.put("corpId", corpId);
        // 表单ID
        textParams.put("formId", formId);
        textParams.put("userId", userId);
        // 获取移动表单
        String configJson = restClient.get("/model/form/mobile/getMobileFormContent", user.getJwtToken(), textParams);
        // 取得返回数据
        Map<String, Object> formContent = JsonUtils.readValue(configJson);
        Map<String, Object> form = new HashMap<>();
        List<Map<String, Object>> realItem = new ArrayList<>();
        if ("0".equals(formContent.get("code"))) {
            // 获取移动表单成功
            String data = (String) formContent.get("data");
            form = JsonUtils.readValue(data);
        }else{
            return ResponseResult.buildFailureResult(formContent.get("message").toString());
        }
        List<Map<String, Object>> addressLists = new ArrayList<>();
        try {
            String scopeMap1 = restClient.get("/model/form/getEditFormData", token, paramMap1);
            Map<String, Object> map1 = JsonUtils.readValue(scopeMap1);
            if (map1.get("type").toString().equals("success")) {
                Map<String, Object> resultMap1 = (Map<String, Object>) map1.get("data");
                List list = (List) resultMap1.get("mainTblData");
                dataMap.put("formData", resultMap1);
                if(list.size()>0){
                    Map<String, Object> resultMap2 = new HashMap<String, Object>();
                    resultMap2.putAll(resultMap1);
                    List<Map<String, Object>> dataList = (List<Map<String, Object>>) resultMap2.get("mainTblData");
                    Iterator it = dataList.iterator();
                    String att_key = "";
                    String att_value = "";
                    RestClient restClient1 = new RestClient();
                    while (it.hasNext()) {
                        Map p = (Map) it.next();
                        //p.put("value",StringUtils.null2String(p.get("value")));
                        if (StringUtils.equals(StringUtils.null2String(p.get("key")), "boardroom_id")) {
                            Map<String,String> paramsMap = new HashMap<String,String>();
                            boardroomId = StringUtils.null2String(p.get("value"));
                            paramsMap.put("id", boardroomId);
                            paramsMap.put("type", "0");
                            String resultJson = restClient1.get("/meeting/boardroomSet/getBoardRoomOrServes", token, paramsMap);
                            Map<String, Object> result = JsonUtils.readValue(resultJson);
                            Map<String, String> map = (Map<String, String>) result.get("data");
                            //p.put("showValue", map.get("name"));
                        } else if (StringUtils.equals(StringUtils.null2String(p.get("key")), "meeting_serve")) {
                            Map<String,String> paramsMap = new HashMap<String,String>();
                            paramsMap.put("id", StringUtils.null2String(p.get("value")));
                            paramsMap.put("type", "1");
                            String resultJson = restClient1.get("/meeting/boardroomSet/getBoardRoomOrServes", token, paramsMap);
                            Map<String, Object> result = JsonUtils.readValue(resultJson);
                            Map<String, String> map = (Map<String, String>) result.get("data");
                            //p.put("showValue", map.get("name"));
                        } else if(StringUtils.equals(StringUtils.null2String(p.get("key")), "start_time")){
                            startTime = StringUtils.null2String(p.get("value"));
                        }else if(StringUtils.equals(StringUtils.null2String(p.get("key")), "end_time")){
                            endTime = StringUtils.null2String(p.get("value"));
                        }else if(StringUtils.equals(StringUtils.null2String(p.get("key")), "end_time")){
                            endTime = StringUtils.null2String(p.get("value"));
                        }else if(StringUtils.equals(StringUtils.null2String(p.get("key")), "emcee_user") ||
                                 StringUtils.equals(StringUtils.null2String(p.get("key")), "memo_user") ||
                                 StringUtils.equals(StringUtils.null2String(p.get("key")), "attend_user")||
                                 StringUtils.equals(StringUtils.null2String(p.get("key")), "meeting_attendants")){
                            p.put("realValue", p.get("value"));
                        }else if(StringUtils.equals(StringUtils.null2String(p.get("key")), "cycle_end_time")) {
                        	cycleEndTime = StringUtils.null2String(p.get("value"));
                        }
                    }
                    Iterator realIit = list.iterator();
                    String cycleType = "", cycleValue = "";
                    while (realIit.hasNext()) {
                        Map p = (Map) realIit.next();
                        if (StringUtils.equals(StringUtils.null2String(p.get("key")), "cycle_type")) {
                        	cycleType = StringUtils.null2String(p.get("value"));
                        } else if (StringUtils.equals(StringUtils.null2String(p.get("key")), "cycle_value")) {
                        	cycleValue = StringUtils.null2String(p.get("value"));
                        } else if(StringUtils.equals(StringUtils.null2String(p.get("key")), "interval_date") && "0".equals(cycleType)) {
                        	p.put("value", cycleValue);
                        } else if(StringUtils.equals(StringUtils.null2String(p.get("key")), "repetitive_week") && "1".equals(cycleType)) {
                        	p.put("value", cycleValue);
                        } else if(StringUtils.equals(StringUtils.null2String(p.get("key")), "repetitive_month")) {
                        	if("2".equals(cycleType)) p.put("value", cycleValue);
                        	else p.put("value", "1");
                        }
                    }
                }else{
                    if(StringUtils.isNotEmpty(dataId)){
                        return ResponseResult.buildFailureResult("表单数据已删除");
                    }
                }
            }else{
                return ResponseResult.buildFailureResult(map1.get("message").toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.buildFailureResult("查询表单接口调用失败");
        }

        String boardroomName="", position="", longitude="", latitude="";
        List<Map> serves = new ArrayList<>();
        if(boardroomId != ""){
            RestClient restClient1 = new RestClient();
            Map<String,String> paramsMap = new HashMap<String,String>();
            paramsMap.put("id", boardroomId);
            paramsMap.put("type", "3");
            paramsMap.put("corpId", corpId);
            String resultJson = restClient1.get("/meeting/boardroomSet/getBoardRoomOrServes", token, paramsMap);
            Map<String, Object> result = JsonUtils.readValue(resultJson);
            Map<String, Object> map = (Map<String, Object>) result.get("data");
            boardroomName = StringUtils.null2String(map.get("name"));
            position = StringUtils.null2String(map.get("position"));
            longitude = StringUtils.null2String(map.get("longitude"));
            latitude = StringUtils.null2String(map.get("latitude"));
            serves = (List<Map>) map.get("serves");
        }
        List<Map<String, Object>> item = (List<Map<String, Object>>)form.get("item");
        for (Map<String, Object> map: item) {
            String itemCode = StringUtils.null2String(map.get("itemCode"));
            String value = StringUtils.null2String(map.get("value"));
            if(itemCode.equals("boardroom_id")){
                List multiItems = new ArrayList();
                Map<String, String> multiItem = new HashMap<>();
                multiItem.put("name", boardroomName);
                multiItem.put("value", boardroomId);
                multiItems.add(multiItem);
                map.put("multiItems", multiItems);
                map.put("value", boardroomId);
                map.put("defaultValue", boardroomId);
                map.put("itemType", "select");
            }else if(itemCode.equals("meeting_serve")){
                map.put("multiItems", serves);
                map.put("itemType", "checkbox");
            }else if(itemCode.equals("start_time")){
                map.put("itemType", "datetimeStep");
                map.put("dateFormat", "YMDHM");
                map.put("selectValue", startTime);
                map.put("defaultValue", startTime);
                map.put("value", startTime);
            }else if(itemCode.equals("end_time")){
                map.put("selectValue", endTime);
                map.put("defaultValue", endTime);
                map.put("value", endTime);
                map.put("itemType", "datetimeStep");
                map.put("dateFormat", "YMDHM");
            }else if(itemCode.equals("is_cycle")|| itemCode.equals("is_sync") || itemCode.equals("is_notice") || itemCode.equals("is_signed")){
            	if(itemCode.equals("is_notice")){
                	String noticeType = commonService.getSysParamValueByMark(corpId, token, "sysImType");
                	map.put("noticeType", noticeType);
                }
            	map.put("itemType", "switch");
                map.put("defaultValue", "0");
                if("".equals(value)){
                    map.put("value", "0");
                }
            }else if(itemCode.equals("is_sync_calendar")){
            	map.put("itemType", "switch");
                map.put("defaultValue", "1");
                if("".equals(value)){
                    map.put("value", "1");
                }
            } else if(itemCode.equals("cycle_type")){
                map.put("defaultValue", "0");
                if("".equals(value)){
                    map.put("value", "0");
                }
            }else if(itemCode.equals("repetitive_week")){
            	List<Map<String, Object>> weekList = new ArrayList<Map<String, Object>>();
            	Map<String, Object> weekMap = null;
            	String week = "";
            	for(int i = 1; i <= 7; i++) {
            		weekMap = new HashMap<String, Object>();
            		if(i == 1) week = "星期天";
            		else if(i == 2) week = "星期一";
            		else if(i == 3) week = "星期二";
            		else if(i == 4) week = "星期三";
            		else if(i == 5) week = "星期四";
            		else if(i == 6) week = "星期五";
            		else if(i == 7) week = "星期六";
            		weekMap.put("name", week);
            		weekMap.put("value", i);
            		weekList.add(weekMap);
            	}
            	map.put("multiItems", weekList);
                map.put("itemType", "checkbox");
            }else if(itemCode.equals("repetitive_month")){
            	List<Map<String, Object>> monthList = new ArrayList<Map<String, Object>>();
            	Map<String, Object> monthMap = null;
            	for(int i = 1; i <= 31; i++) {
            		monthMap = new HashMap<String, Object>();
            		monthMap.put("name", i + "日");
            		monthMap.put("value", i);
            		monthList.add(monthMap);
            	}
                map.put("multiItems", monthList);
                map.put("itemType", "select");
                map.put("defaultValue", "1");
                if("".equals(value)){
                    map.put("value", "1");
                }
            }else if(itemCode.equals("cycle_end_time")){
            	String time = StringUtils.isNotEmpty(cycleEndTime) ? cycleEndTime : DateUtils.formatDate(new Date(), "yyyy-MM-dd");
            	map.put("itemType", "datetimeStep");
                map.put("dateFormat", "YMD");
                map.put("selectValue", time);
                map.put("defaultValue", time);
                map.put("value", time);
            }else if(itemCode.equals("message_push")){
            	String messagePushSW = commonService.getMessagePush(corpId, token,"meeting");
            	map.put("messagePushSW", messagePushSW);
            }else if(itemCode.equals("notice_time")){
            	String noticeType = commonService.getSysParamValueByMark(corpId, token, "sysImType");
            	map.put("noticeType", noticeType);
                map.put("defaultValue", "10");
                if("".equals(value)){
                    map.put("value", "10");
                }
            }else if(itemCode.equals("signed_type")){
                map.put("defaultValue", "0");
                if("".equals(value)){
                    map.put("value", "0");
                }
            }else if(itemCode.equals("signed_range")){
                map.put("defaultValue", "100");
                if("".equals(value)){
                    map.put("value", "100");
                }
            }else if(itemCode.equals("signed_time")){
                map.put("defaultValue", "10");
                if("".equals(value)){
                    map.put("value", "10");
                }
            }else if(itemCode.equals("oa_meeting_signed_addr")){//签到地址
                List<Map<String, Object>> children = (List<Map<String, Object>>)map.get("children");
                List<Map<String, Object>> realChildren = new ArrayList<>();
                if(children!=null && children.size()>0){
                    for (Map<String, Object> child: children) {
                        String childItemCode = StringUtils.null2String(child.get("itemCode"));
                        if(StringUtils.isEmpty(dataId)){
                            if(childItemCode.equals("signed_address")){
                                child.put("itemType", "positioning");
                                child.put("defaultValue", position);
                                child.put("value", position);
                            }else if(childItemCode.equals("longitude")){
                                child.put("defaultValue", StringUtils.isBlank(longitude) ? "0" : longitude);
                                child.put("value", StringUtils.isBlank(longitude) ? "0" : longitude);
                            }else if(childItemCode.equals("latitude")){
                                child.put("defaultValue", StringUtils.isBlank(latitude) ? "0" : latitude);
                                child.put("value", StringUtils.isBlank(latitude) ? "0" : latitude);
                            }
                        }
                        realChildren.add(child);
                    }
                }
                map.put("children", realChildren);
            }
            realItem.add(map);
        }
        form.put("item", realItem);
        dataMap.put("form", form);

        //查找流程详情
        String isCanDealwith = "0";
        Map<String, String> paramMap2 = new HashMap<String, String>();
        paramMap2.put("corpId", corpId);
        paramMap2.put("userId", userId);
        String urlName = "";
        if (type.equals("0")) {//待办
            paramMap2.put("taskId", taskId);
            paramMap2.put("lock", "1");
            urlName = "/bpm/runtime/getUndoTaskInfo";
        }else if(type.equals("1")){//待阅
        	paramMap2.put("processInstanceId", processInstanceId);
            urlName = "/bpm/runtime/getProcessInfo";
        }else if(type.equals("2")){//已办
//            paramMap2.put("taskId", taskId);
//            urlName = "/bpm/runtime/getProcessInfo";
        }else if(type.equals("3")){//已阅
        	paramMap2.put("processInstanceId", processInstanceId);
            urlName = "/bpm/runtime/getProcessInfo";
        }else{
            paramMap2.put("processInstanceId", processInstanceId);
            urlName = "/bpm/runtime/getProcessInfo";
        }
        
        //paramMap2.put("processInstanceId", processInstanceId);
        //流程列表展示
        List<Map<String, Object>> processList = new ArrayList<Map<String, Object>>();
        try {
        	String scopeMap2 = "";
        	if(!type.equals("2")) {
        		scopeMap2 = restClient.get(urlName, token, paramMap2);
                map2 = JsonUtils.readValue(scopeMap2);
        	}
            if (map2.get("type").toString().equals("success")) {
                if (type.equals("0")) {//待办
                    Map<String, Object> resultMap2 = (Map<String, Object>) map2.get("data");
                    dataMap.put("processType", resultMap2.get("processType"));
                    dataMap.put("code", resultMap2.get("code"));
                    String userIds = "";

                    dataMap.put("processIsComplete", "0");

                    //dataMap.put("doneUserList", resultMap2.get("doneUserList"));

                    Map<String,Object> fieldControll = new HashMap<String,Object>();
                    //不知为何移动端，会把间隔日期，重复周等变为只读。这样发起预定会议室的时候就不能选择了
                    String showFields = resultMap2.get("showFields") == null ? null : resultMap2.get("showFields").toString() ;//+ ",oa_meeting_apply_record_interval_date,oa_meeting_apply_record_repetitive_week,oa_meeting_apply_record_repetitive_month";
                    fieldControll.put("showFields", showFields);
                    fieldControll.put("editFields", resultMap2.get("editFields"));
                    fieldControll.put("hiddenFields", resultMap2.get("hiddenFields"));
                    fieldControll.put("mustFields", resultMap2.get("mustFields"));
                    dataMap.put("fieldControll",fieldControll);

                    //是否有批示意见
                    if (resultMap2.get("commentField") != null && resultMap2.get("commentField") != "null") {
                        dataMap.put("hasCommentField", '1');
                    } else {
                        dataMap.put("hasCommentField", '0');
                    }

                    //批示意见列表
                    if (resultMap2.get("commentList") != null) {
                        dataMap.put("commentList",  dealwithComment((List<Map<String,Object>>) resultMap2.get("commentList"),corpId,token));
                    } else {
                        dataMap.put("commentList", new ArrayList());
                    }

                    //按钮(待办的时候)
                    if (resultMap2.get("buttons") != null) {
                        dataMap.put("buttons", resultMap2.get("buttons"));
                    } else {
                        dataMap.put("buttons", "");
                    }

                    //流程锁(待办的时候)
                    if (resultMap2.get("lock") != null) {
                        dataMap.put("lock", resultMap2.get("lock"));
                    } else {
                        dataMap.put("lock", "");
                    }

                    //节点类型(0：单人，1：会签，2：串签)
                    if (resultMap2.get("participantMode") != null) {
                        dataMap.put("participantMode", resultMap2.get("participantMode"));
                    }else {
                        dataMap.put("participantMode", "");
                    }
                    //是否紧急
                    if (resultMap2.get("urgency") != null) {
                        dataMap.put("urgency", resultMap2.get("urgency"));
                    }else {
                        dataMap.put("urgency", "0");
                    }

                    //是否是开始节点
                    if(resultMap2.get("isStart") != null){
                        dataMap.put("isStart", resultMap2.get("isStart").toString().equals("true")?true:false);
                    }else{
                        dataMap.put("isStart", false);
                    }


                    //随机流程
                    if(resultMap2.get("tasktype") != null){
                        dataMap.put("tasktype", resultMap2.get("tasktype").toString());
                        dataMap.put("level", resultMap2.get("level").toString());
                        dataMap.put("levelCount", resultMap2.get("levelCount").toString());
                    }else{
                        dataMap.put("tasktype", "");
                    }
                    isCanDealwith = "1";

                    //标题
                    if (resultMap2.get("title") != null) {
                        dataMap.put("title", resultMap2.get("title"));
                    } else {
                        dataMap.put("title", "");
                    }

//                    Map param3 = new HashMap();
//                    param3.put("userId", user.getUserId());
//                    param3.put("corpId", user.getCorpId());
//                    param3.put("taskId", taskId);
//                    String flowListJson = restClient.get("/bpm/getProcessInfo",token, param3);
//                    Map<String,Object> flowListMap = JsonUtils.readValue(flowListJson);
                } else {//已办我的
                    Map<String, Object> resultMap2 = (Map<String, Object>) map2.get("data");
                    dataMap.put("processType", resultMap2.get("processType"));
                    dataMap.put("code", resultMap2.get("code"));
                    String userIds = "";
                    if (resultMap2.get("doingUserList") != null) {
                        List<Map<String, Object>> doingUserList = (List<Map<String, Object>>) resultMap2.get("doingUserList");
                        if (doingUserList!=null && doingUserList.size() > 0) {

                            for (Map<String, Object> doingUser : doingUserList) {
                                String doingUserId = doingUser.get("userId").toString();
                                String doingTaskId = doingUser.get("taskId").toString();
                                if (type.equals("0")) {//待办
                                    if (doingTaskId.equals(taskId) && doingUserId.equals(userId)) {
                                        isCanDealwith = "1";
                                    }
                                }

                                userIds += doingUser.get("userId").toString() + ",";
                            }
                            if (StringUtils.isNoneBlank(userIds)) {
                                userIds = userIds.substring(0, userIds.length() - 1);
                            }
                            List<String> userMap = userApiService.getUserIdBySysOrThird( userIds,"1","DD",corpId, token);
                            //handleUserDingId = userMap.get("thirdUId").toString();
                            dataMap.put("handleUserDingId", userMap);
                        } else {
                            dataMap.put("handleUserDingId", new ArrayList());
                        }
                    } else {
                        dataMap.put("handleUserDingId", new ArrayList());
                    }

                    if (resultMap2.get("processEndTime") != null) {
                        dataMap.put("processIsComplete", "1");
                    } else {
                        dataMap.put("processIsComplete", "0");
                    }

                    //在办用户列表
                    if (resultMap2.get("doingUserList") != null) {
                        dataMap.put("doingUserList", resultMap2.get("doingUserList"));
                    } else {
                        dataMap.put("doingUserList", resultMap2.get("doingUserList"));
                    }

                    //已办记录
                    if (resultMap2.get("processLogList") != null) {
                        dataMap.put("processLogList", resultMap2.get("processLogList"));
                    } else {
                        dataMap.put("processLogList", resultMap2.get("processLogList"));
                    }

                    //批示意见
                    if (resultMap2.get("commentList") != null) {
                        dataMap.put("commentList", dealwithComment((List<Map<String,Object>>) resultMap2.get("commentList"),corpId,token));
                    } else {
                        dataMap.put("commentList", new ArrayList());
                    }

                    //按钮
                    if (resultMap2.get("buttons") != null) {
                        dataMap.put("buttons", resultMap2.get("buttons"));
                    } else {
                        dataMap.put("buttons", "");
                    }

                    //起始节点按钮
                    if (resultMap2.get("startButtons") != null) {
                        dataMap.put("startButtons", resultMap2.get("startButtons"));
                    } else {
                        dataMap.put("startButtons", "");
                    }

                    if(type.equals("1")) {//已办的表单详情控制隐藏
                        Map<String, String> hm = new HashMap<String, String>();
                        hm.put("userId", user.getUserId());
                        hm.put("corpId", user.getCorpId());
                        hm.put("taskId", taskId);
                        hm.put("formId", formId);
                        String json = restClient.get("/bpm/runtime/getReadTaskInfo", user.getJwtToken(), hm);
                        Map<String, Object> hm1 = JsonUtils.readValue(json);
                        Map<String,Object> readMap = (Map<String, Object>) hm1.get("data");

                        Map<String, Object> fieldControll = new HashMap<String, Object>();
                        fieldControll.put("hiddenFields", readMap.get("hiddenFields"));
                        fieldControll.put("mobileFields", readMap.get("mobileFields"));
                        dataMap.put("fieldControll", fieldControll);
                        //是否有批示意见
                        if (readMap.get("commentField") != null && readMap.get("commentField") != "null" && StringUtils.equals(readMap.get("owntype").toString(),"read")) {
                            dataMap.put("hasCommentField", '1');
                        } else {
                            dataMap.put("hasCommentField", '0');
                        }
                    }
                    Map<String, String> hmParam = new HashMap<String, String>();
                    hmParam.put("taskId", taskId);
                    RestClient restClient2 = new RestClient(false);
                    String json2 = restClient2.get("/approve/getReadTypeByTaskId", user.getJwtToken(), hmParam);
                    Map<String, Object> hm2 = JsonUtils.readValue(json2);
                    //判断是否已阅，1，未阅，2是已阅
                    dataMap.put("readtype", hm2.get("message"));
                    
                    //流程状态，0未结束，1结束，3，作废，4，取消
                    if (resultMap2.get("status") != null) {
                        dataMap.put("processStatus", resultMap2.get("status"));
                    } else {
                        dataMap.put("processStatus", "0");
                    }

                    //标题
                    if (resultMap2.get("title") != null) {
                        dataMap.put("title", resultMap2.get("title"));
                    } else {
                        dataMap.put("title", "");
                    }
                }
            } else {
                //dataMap.put("handleUserDingId", new ArrayList());
                return ResponseResult.buildFailureResult(map2.get("message").toString());
            }


            //查询创建人
//			if(StringUtils.isNotBlank(startUserId)){
//				Map<String, Object> createUserInfo = userApiService.getUserMainOrgStaData(startUserId,"",corpId,token);
//				String createUserName = createUserInfo.get("userName").toString();
//				String createOrgName = createUserInfo.get("orgName").toString();
//				dataMap.put("createUserName", createUserName);
//				dataMap.put("createOrgName", createOrgName);
//			}
            

        } catch (Exception e) {
            e.printStackTrace();
            //记录日志
            if(StringUtils.isNotEmpty(logCode) && title != null && logService.checkOptLog(corpId, logCode, user.getJwtToken())) //判断是否记录日志
            	this.logService.saveModuleLog(logCode, title, "", UuidUtils.UUID());  
            return ResponseResult.buildFailureResult("流程详情接口调用失败");
        }
        dataMap.put("isCanDealwith", isCanDealwith);
        dataMap.put("processList", processList);
        //获取系统设置参数  水印
        String sysWatermark = commonService.getSysParamValueByMark(corpId, token,"sysWatermark");
        if(StringUtils.isNoneBlank(sysWatermark) && sysWatermark.indexOf("bpm")>-1) {//标识流程表单需要显示水印
          sysWatermark = user.getCnName()+user.getUserName();
        }else {
          sysWatermark = "";
        }
        dataMap.put("sysWatermark", sysWatermark);
        //获取签到方式和会议方式配置
        Map<String,Object>formData=(Map<String,Object>)dataMap.get("formData");
        if(formData==null) {
        	formData=new HashMap<>();
        	dataMap.put("formData", formData);
        }
        BaseSet baseSet = this.service.getBaseSetInfo(corpId);
        String signedType = baseSet.getSignedType();
        String meetingWay = baseSet.getMeetingWay();
        String signedTypeStr = "";
        if(signedType!=null) {
        	signedTypeStr += "[";
        	if(signedType.indexOf("|0|")!=-1){
        		signedTypeStr += "{ value: '0', text: '扫码' },";
		    }
		   if(signedType.indexOf("|1|")!=-1){
			   signedTypeStr += "{ value: '1', text: '定位' },";
		   }
		   if(signedType.indexOf("|2|")!=-1){
			   signedTypeStr += "{ value: '2', text: '扫码+定位' },";
		   }
		   if(signedType.indexOf("|3|")!=-1){
			   signedTypeStr += "{ value: '3', text: '现场签到' },";
		   }
		   if(signedTypeStr.endsWith(",")) signedTypeStr = signedTypeStr.substring(0,signedTypeStr.length()-1);
		   signedTypeStr += "]";
        }
        formData.put("signedTypeStr", signedTypeStr);
        String meetingWayStr = "";
        if(meetingWay!=null) {
        	String[] ways=meetingWay.split(",");
        	meetingWayStr += "[";
        	for(int i=0;i<ways.length;i++) {
        		if("0".equals(ways[i])) {
        			meetingWayStr += "{ value: '0', text: '现场会议' },";
            	}else if("1".equals(ways[i])) {
            		meetingWayStr += "{ value: '1', text: '网络会议' },";
            	}else if("2".equals(ways[i])) {
            		meetingWayStr += "{ value: '2', text: '现场+网络' },";
            	}
        	}
        	if(meetingWayStr.endsWith(",")) meetingWayStr = meetingWayStr.substring(0,meetingWayStr.length()-1);
        	meetingWayStr += "]";
        }
        formData.put("meetingWayStr", meetingWayStr);
        
        //记录日志
        if(StringUtils.isNotEmpty(logCode) && title != null && logService.checkOptLog(corpId, logCode, user.getJwtToken())) //判断是否记录日志
        	this.logService.saveModuleLog(logCode, title, "");  
        return ResponseResult.buildSuccessResult(dataMap);
    }

    /**
     * 处理批示意见显示
     * @param commentList
     * @return
     */
//    public List<Map<String,Object>> dealwithComment(List<Map<String,Object>> commentList,String corpId,String token){
//    	RestClient restClient = new RestClient(true);
//    	for(int i=0; i<commentList.size(); i++){
//            Map<String,Object> comment = commentList.get(i);
//            String type = StringUtils.null2String(comment.get("type"));
//            if ("text0".equals(type)) {//姓名+日期时间
//            }else if("text1".equals(type)){//姓名+日期
//                String time = StringUtils.null2String(comment.get("time"));
//                if(StringUtils.isNotBlank(time)){
//                    time = time.substring(0,10);
//                    comment.put("time",time);
//                }
//            }else if("text2".equals(type)){//签名图片+日期时间
//                String userId = StringUtils.null2String(comment.get("userId"));
//                Map<String, Object> user = userApiService.getUser(userId,corpId,"",token);
//                String signPic = StringUtils.null2String(user.get("signPic"));
//                if(StringUtils.isNotBlank(signPic)){
//                    comment.put("signPic",signPic);
//                }else{
//                    comment.put("signPic","");
//                }
//            }else if("text3".equals(type)){//签名图片+日期
//                String time = StringUtils.null2String(comment.get("time"));
//                if(StringUtils.isNotBlank(time)){
//                    time = time.substring(0,10);
//                    comment.put("time",time);
//                }
//                String userId = StringUtils.null2String(comment.get("userId"));
//                Map<String, Object> user = userApiService.getUser(userId,corpId,"",token);
//                String signPic = StringUtils.null2String(user.get("signPic"));
//                if(StringUtils.isNotBlank(signPic)){
//                    comment.put("signPic",signPic);
//                }else{
//                    comment.put("signPic","");
//                }
//            }else if(type.indexOf("image")!=-1){
//            	 Object fullMessage=comment.get("fullMessage");
//            	 if(fullMessage!=null){
//            		 Map<String, String> paramMap=new HashMap<String,String>();
//            		 paramMap.put("corpId", corpId);
//            		 paramMap.put("recordId", fullMessage+"");
//            		 String scopeMap = restClient.get("/cmp/goldgrid/redocument/getReDocumentFileMap",token, paramMap);
//            		 Map<String,Object> map = JsonUtils.readValue(scopeMap);
//            		 comment.put("fullMessage","");
//            		 if(map.get("type").toString().equals("success")){
//            			 Map<String,Object> data = (Map<String, Object>) map.get("data");
//            			 String code=data.get("code").toString();
//            			 if(StringUtils.equals("0", code)){
//            				 Map<String,Object> attachment = (Map<String, Object>) data.get("attachment");
//            				 comment.put("fullMessage",attachment.get("id"));
//            			 }
//            		 }
//            	 }else{
//            		 comment.put("fullMessage","");
//            	 }
//            }
//        }
//        return commentList;
//    }
	
    /**
     * 处理批示意见显示
     * @param commentList
     * @return
     */
    public List<Map<String,Object>> dealwithComment(List<Map<String,Object>> commentList,String corpId,String token){
    	RestClient restClient = new RestClient(true);
    	for(int i=0; i<commentList.size(); i++){
            Map<String,Object> comment = commentList.get(i);
            String type = StringUtils.null2String(comment.get("type"));
            if ("text0".equals(type)) {//姓名+日期时间
            }else if("text1".equals(type)){//姓名+日期
                String time = StringUtils.null2String(comment.get("time"));
                if(StringUtils.isNotBlank(time)){
                    time = time.substring(0,10);
                    comment.put("time",time);
                }
            }else if("text2".equals(type)){//签名图片+日期时间
                String userId = StringUtils.null2String(comment.get("userId"));
                Map<String, Object> user = userApiService.getUser(userId,corpId,"",token);
                String signPic = StringUtils.null2String(user.get("signPic"));
                if(StringUtils.isNotBlank(signPic)){
                    comment.put("signPic",signPic);
                }else{
                    comment.put("signPic","");
                }
            }else if("text3".equals(type)){//签名图片+日期
                String time = StringUtils.null2String(comment.get("time"));
                if(StringUtils.isNotBlank(time)){
                    time = time.substring(0,10);
                    comment.put("time",time);
                }
                String userId = StringUtils.null2String(comment.get("userId"));
                Map<String, Object> user = userApiService.getUser(userId,corpId,"",token);
                String signPic = StringUtils.null2String(user.get("signPic"));
                if(StringUtils.isNotBlank(signPic)){
                    comment.put("signPic",signPic);
                }else{
                    comment.put("signPic","");
                }
            }else if(type.indexOf("image")!=-1){
            	 Object fullMessage=comment.get("fullMessage");
            	 if(fullMessage!=null){
            		 Map<String, String> paramMap=new HashMap<String,String>();
            		 paramMap.put("corpId", corpId);
            		 paramMap.put("recordId", fullMessage+"");
            		 String scopeMap = restClient.get("/cmp/goldgrid/redocument/getReDocumentFileMap",token, paramMap);
            		 Map<String,Object> map = JsonUtils.readValue(scopeMap);
            		 comment.put("fullMessage","");
            		 if(map.get("type").toString().equals("success")){
            			 Map<String,Object> data = (Map<String, Object>) map.get("data");
            			 String code=data.get("code").toString();
            			 if(StringUtils.equals("0", code)){
            				 Map<String,Object> attachment = (Map<String, Object>) data.get("attachment");
            				 comment.put("fullMessage","fid="+attachment.get("id")+"&chksum="+attachment.get("checksum"));
            			 }
            		 }
            	 }else{
            		 comment.put("fullMessage","");
            	 }
            }
        }
        return commentList;
    }
    
    /**
     * 发送提醒功能
     */
    @ApiOperation(value = "发送提醒", notes = "发送提醒")
    @RequestMapping(value = "/sendMeetingRemind", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult sendMeetingRemind(HttpServletRequest request) {
         try {
	    	WebUser user = WebUtils.getCurrentUser();
	    	String token = user.getJwtToken();
	    	String applyRecordId = request.getParameter("applyRecordId");
    		String userId = user.getUserId();
    		String userName = user.getCnName();
    		String userOrg = user.getOrgId();
    		String corpId = user.getCorpId();
    		String context = request.getParameter("context");
    		String userArrays = request.getParameter("userArrays");
    		ApplyRecord applyRecord = applyRecordService.findOne(applyRecordId);
	    	Map<String, Object> ds = new HashMap<>();
            ds.put("applyRecordId", applyRecordId);
            if(applyRecord != null) {
            	ds.put("meetingTitle", applyRecord.getName());
            }else {
            	ds.put("meetingTitle", "");
            }
     		ds.put("meetingRemindContext", context);
     		ds.put("userId", userId);
     		ds.put("userName", userName);
     		ds.put("userOrg", userOrg);
     		ds.put("type", "10");
     		ds.put("userIds", userArrays);
            ds.put("orgIds", null);
            boolean mobilePush = false;
            boolean emailPush = false;
            boolean smsPublish = false;
			String mesgPush = applyRecord.getMessagePush();
			if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
			if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
			if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
    		this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
            this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, token, request);
			this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, token);
            String jsonIds = "[";
            if(StringUtils.isNotEmpty(userArrays)) {
            	String[] userIds = userArrays.split(",");
            	for(String ids : userIds) {
            		jsonIds += "{\"10\":\"" + ids + "\"}";
            	}
            }
            jsonIds += "]";
            this.meetingSendMsgUtils.sendMessage(ds, jsonIds, corpId, token);
	    } catch (Exception e) {
	        e.printStackTrace();
	        return ResponseResult.buildFailureResult("发送失败");
	    }
        return ResponseResult.buildSuccessResult("发送成功");
    }
    
    @ApiOperation(value = "纪要转发功能", notes = "纪要转发功能")
    @RequestMapping(value = "/transmitMemo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult transmitMemo(HttpServletRequest request) {
        try {
        	WebUser user = WebUtils.getCurrentUser();
            String corpId = user.getCorpId();
            String token = user.getJwtToken();
            String memoId =  request.getParameter("memoId");
            String jsonStrTransmiScope =  request.getParameter("jsonStrTransmiScope");
            List<String> addList = null;
			if(StringUtils.isNotEmpty(jsonStrTransmiScope)) {
				JSONArray json = (JSONArray) JSONArray.parse(jsonStrTransmiScope);
			    if(json != null) {
			    	String userId = "", orgId = "", type = "";
			    	Set<String> userIdList = new HashSet<String>();
			    	for(int i = 0; i < json.size(); i++) {
			    		JSONObject jo = (JSONObject)json.get(i);
			    		type = jo.getString("scopeType");
			    		if("user".equals(type)) {
			    			userId = jo.getString("scopeValue");
			    			userIdList.add(userId);
			    		}else if("org".equals(type)) {
			    			orgId = jo.getString("scopeValue");
			    			List<String> unitUserList = this.userApiService.getUserIdsByOrgId(orgId, "", "1", corpId, token);
			                if(unitUserList!=null && unitUserList.size()>0){
			                	userIdList.addAll(unitUserList);
			                }
			    		}
			    	}
			    	addList = new ArrayList<String>(userIdList);
			    }
			    this.memoUserInfoService.addMemoUserInfo(memoId, addList, corpId);
			}
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.buildSuccessResult("转发成功");
        }
        return ResponseResult.buildSuccessResult("转发失败");
    }
    
    @ApiOperation(value = "删除会议纪要", notes = "删除会议纪要")
    @RequestMapping(value = "/deleteMemoInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult deleteMemoInfo(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
        	WebUser user = WebUtils.getCurrentUser();
            String corpId = user.getCorpId();
            String memoId =  request.getParameter("memoId");
            
            List<MemoUserInfo> list = this.memoUserInfoService.getMemoUserInfoByMemoId(memoId, corpId);
			this.memoUserInfoService.delete(list);
			MemoInfo mi = memoInfoService.findOne(memoId);
			this.memoInfoService.delete(mi);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.buildSuccessResult("删除失败");
        }
        return ResponseResult.buildSuccessResult("删除成功");
    }
    
    /**
     * 计算有效时间
     * @param dateTime
     * @param data
     * @param type
     * @return
     */
    public String getDateTimeStr(String dateTime, int data,int type) {
        String hourStr = "";
        String minStr = "";
        String[] arr = dateTime.split(":");
        int hour =Integer.valueOf(arr[0]);
        int min = Integer.valueOf(arr[1]);
        if(type==0){//相加计算
            hour = hour + (data+min)/60;
            min =(data+min)-(data+min)/60*60;
        }else if(type==1){//相减计算
            for(int i=0;i<hour;i++){
                if(((i*60+min)-data)>0){
                    hour = (hour-i);
                    min = (i*60+min)-data;
                    break;
                }
            }
        }
        if(hour<10){
            hourStr = "0" + hour;
        }else{
            hourStr = "" + hour;
        }
        if(min<10){
            minStr = "0" + min;
        }else{
            minStr = "" + min;
        }
        return hourStr + ":"+ minStr;
    }
    
    /**
     * 给转交人推送消息
     * @param request
     * @param entity
     * @param userId
     * @param corpId
     */
    private void sendMessageToTurnoverUser(HttpServletRequest request, ApplyRecord entity, String sendUserId, String turnoverUserId, String corpId, String token) {
    	Map<String, Object> ds = new HashMap<>();
        ds.put("applyRecordId", entity.getId());
 		ds.put("meetingTitle", entity.getName());
 		ds.put("startTime", entity.getStartTime());
 		BoardroomSet room = this.boardroomSetService.findOne(entity.getBoardroomId());
 		if(room != null) ds.put("boardroom", room == null ? (StringUtils.isNotEmpty(entity.getAddress()) ? entity.getAddress():"无") : room.getAddress());
        String userName = "";
        Map<String, Object> userInfo = this.userApiService.getUser(sendUserId, corpId,  "", TOKEN);
        if(userInfo != null){
            userName = StringUtils.null2String(userInfo.get("userName"));
        }
 		ds.put("userId", sendUserId);
 		ds.put("userName", userName);
 		ds.put("userOrg", "");
 		ds.put("type", "8");
 		ds.put("userIds", turnoverUserId);
        ds.put("orgIds", null);
        boolean mobilePush = false;
        boolean emailPush = false;
        boolean smsPublish = false;
		String mesgPush = entity.getMessagePush();
		if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
		if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
		if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
		this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
        this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, token, request);
		this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, token);
        String jsonIds = "[{\"10\":\"" + turnoverUserId + "\"}]";
        this.meetingSendMsgUtils.sendMessage(ds, jsonIds, corpId, token);
    }
    
    /**
	 * 根据选人组件(单选)json获取id,name
	 * @param jsonStr
	 * @return
	 */
	private Map<String, String> getUserId(String jsonStr) {
		Map<String, String> map = new HashMap<String, String>();
		JSONArray json = (JSONArray) JSONArray.parse(jsonStr);
	    if(json != null && json.size() > 0) {
	    	JSONObject jo = (JSONObject)json.get(0);
	    	map.put("id", jo.getString("scopeValue"));
	    	map.put("name", jo.getString("scopeName"));
	    }
	    return map;
	}
	
	/**
	 * 二维码扫码路由
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/murl", method = RequestMethod.GET, produces = { "application/json; charset=UTF-8" })
	public ResponseResult urlConvert(HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try {
			String url = "";
			String id = request.getParameter("id");
			Urlconvert urlconvert = this.urlconvertService.findOne(id);
			String agent = request.getHeader("User-Agent").toLowerCase();
			if (agent.indexOf("dingtalk") > 0) {// 钉钉扫码
//				String appUrl = GlobalConstant.getConfig("app.mobile.ding.front.url");
				url = urlconvert.getDingUrl();
			} else if (agent.indexOf("micromessenger") > 0) {// 企业微信扫码
//				String wxUrl = GlobalConstant.getConfig("app.mobile.weixin.front.url");
				url = urlconvert.getWxUrl();
			} else if (agent.indexOf("emp") > 0) {// 移动平台扫码
//				String webOutUrl = GlobalConstant.getConfig("app.mobile.menhu.front.url");
				url = urlconvert.getMhUrl();
			}
			//response.sendRedirect(url);
			resultMap.put("url", url);
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("content", "");
		}
		return ResponseResult.buildSuccessResult(resultMap);
	}
	
	@RequestMapping(value = "/getCreatedbyNameAndApplyInfo", method = RequestMethod.GET)
	public ResponseResult getCreatedbyNameAndApplyInfo(@RequestParam("id") String id) {
		WebUser user = WebUtils.getCurrentUser();
		String messagePushSW = commonService.getMessagePush(user.getCorpId(), user.getJwtToken(),"meeting");
		ApplyRecord applyRecord=applyRecordService.findOne(id);
		Map<String,Object>reMap=new HashMap<>();
		String createdName=cmpPopUserOrgName.getUserNameById(applyRecord.getCreatedBy());
		reMap.put("createdName", createdName);
		reMap.put("name", applyRecord.getName());
		reMap.put("messagePushSW", messagePushSW);
		return ResponseResult.buildSuccessResult(reMap);
	}
	

}